Vue ComponentsはVueの機能を再利用するための仕組み。
globalに定義する
Vue.componentsに記述する。
data
には初期化処理の関数を書く。data
メンバに関数を指定するのは違和感もあるが、そういう仕様。
template
メンバにはcomponentが置き換えるhtml文を書く。
Vue.component("button-counter",{ data:function() { return {count:0} }, template: '<button v-on:click="count++"> count up {{count}}</button>' })
htmlには<button-counter>
タグを指定することで、template
部分の文が展開される。
<!-- button-counterが設置される。複数設置することもできる。 --> <button-counter></button-counter>
localに定義する
globalに定義するのは何かと弊害もあるので、変数としてlocalに定義することもできる。この場合、Vueインスタンスの引数にcomponents
メンバに記述する。
const buttonCounterLocal = { data:function() { return {count:0} }, template: '<button v-on:click="count++"> count up {{count}} </button>' } const app = new Vue({ el:'#app', components:{ 'button-counter-local': buttonCounterLocal } })