Vue を触ってみる

f:id:utouto97:20210725220659j:plain

Vue CLI で作ったプロジェクトのファイルを見てみよう

まずは、main.jsを見てみましょう。

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

createApp() は、Vueのインスタンスを作成することで、Vueのアプリケーションが始まります。
App.vueをインポートして、mount()してますので、App.vueを見てみます。

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App"/>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

<template> ~ </template><script> ~ </script><style> ~ </style>と分かれています。
それぞれ、テンプレート構文で要素のタグ等を書く部分、スクリプトを書く部分、スタイルを書く部分となっています。

コンポーネントとして、共通部分を別ファイルに書き出すこともできます。
その場合、<script> ~ </script> でインポートして、exports defaultの中で、componentsとしてエクスポートすることで、テンプレートの中で使えるようになります。
今回の例だと、HelloWorldコンポーネントがそれにあたります。

カスタマイズしてみる

まずは、コンポーネントを追加してみます。
src/components/HelloVue.vueを作成します。

<template>
  <div>
    <h1>HELLO VUE !!</h1>
    <div>
      {{msg}}
    </div>
  </div>
</template>

<script>
export default {
  name: 'HelloVue',
  props: {
    msg: String
  }
}
</script>

propsとは、タグの引数のことです。

この HelloVue コンポーネントは、msgという引数をとり、"HELLO VUE !!"という文字列とmsgの内容を表示するコンポーネントです。

App.vueでHelloVueコンポーネントを利用します。

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App"/>
  <HelloVue msg = "VueVueVueVueVueVue" />
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import HelloVue from './components/HelloVue.vue'

export default {
  name: 'App',
  components: {
    HelloWorld,
    HelloVue
  }
}
</script>

これで画面は↓のようになります。
"HELLO VUE !!"という文字列とmsgの内容がページ下部に表示されました。

f:id:utouto97:20210901234107p:plain

終わり