はじめに
Vue.jsを最近勉強し始めたので学んだ文法などを備忘録としてメモしていこうと思います。
前回Vue CLIを用いてVueプロジェクトを立ち上げたので、今回はコンポーネントを作ってみました。
フォルダ構成
componentsフォルダにてそれぞれの挨拶を返却するコンポーネントを作成しており、それらをApp.vueが受け取ってindex.htmlで出力しているという流れになっています。
サンプルコード
以下はMorning.vueの中身です。Afternoon.vueとEvening.vueの中身も挨拶部分以外は同じ作りになっています。
Morning.vue
<template>
<div>
{{ message }}
<button @click="greeting">おはようボタン</button>
</div>
</template>
<script>
export default {
data() {
return {
message: 'おはよう~!'
}
},
methods:{
greeting(){
alert(this.message);
}
}
};
</script>
それぞれのコンポーネントを以下のApp.vueで定義しています。
App.vue
<template>
<div>
<morning></morning>
<afternoon></afternoon>
<evening></evening>
</div>
</template>
<script>
import Morning from './components/Morning.vue';
import Afternoon from './components/Afternoon.vue';
import Evening from './components/Evening.vue';
export default {
components: {
Morning,
Afternoon,
Evening
}
}
</script>
出力結果
上記のコードでnpm run serve
を実行するとアプリが立ち上がり、ボタンをクリックすると以下のように設定したアラートが出力されます。
(以下は「こんにちは」ボタンをクリックしたとき)
おわりに
簡単ではありますがVue.jsのコンポーネントを触ってみました!
自分でコンポーネントを作って親子関係にまとめていけるのは大規模なアプリを作る上ではとても助かりますね!