青ポスの部屋

旅と技術とポエムのブログ

Vue.js (3) Vue Components

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
    }
})

参考

jp.vuejs.org