こんにちは、ミナトです。
「Vue.jsでUI部品を再利用したい」
このような時は、Vue.jsではコンポーネントを利用することで、再利用可能なVueインスタンスを定義できます。
今回はVue.jsのコンポーネントの基本的な使い方について解説します。
目次
コンポーネントのとは
コンポーネントはHTMLで記述されたテンプレートとJavaScriptで記述されたロジックからなる設計図のようなものです。
設計図を元に複数のインスタンスを作成でき、再利用性やメンテナンス性が高まります。
コンポーネントの定義
グローバル登録
グローバルにコンポーネントを登録することで全てのVueインスタンスから利用できます。
以下の例では「hello, world」と表示するコンポーネントを定義して、3つ表示しています。
<div id="app">
<hello-component></hello-component>
<hello-component></hello-component>
<hello-component></hello-component>
</div>
Vue.component('hello-component', {
template: `<p>hello, world</p>`
})
new Vue({
el: '#app',
})
ローカル登録
ローカル登録をすることで、特定のVueインスタンス配下でのみ利用可能とすることもできます。
ローカル定義するためには、Vueインスタンスのcomponentsプロパティに定義したコンポーネントをセットします。
<div id="app">
<hello-component></hello-component>
<hello-component></hello-component>
<hello-component></hello-component>
</div>
var helloComponent = {
template: `<p>hello, world</p>`
}
new Vue({
el: '#app',
components: {
'hello-component': helloComponent
}
})
コンポーネントの定義の注意事項
単一のルートである必要がある
コンポーネントのルート要素は単一である必要があります。
NGパターン
<h3>{{ title }}</h3>
<div v-html="content"></div>
OKパターン
以下のようにルートが一つとなるように親要素でラップします。
<div class="blog-post">
<h3>{{ title }}</h3>
<div v-html="content"></div>
</div>
data は関数である必要がある
NGパターン
Vue.component('click-counter', {
data: {
count: 0
},
template: '<button v-on:click="count += 1">{{ count }}</button>'
})
OKパターン
以下のようにdataプロパティは関数で定義する必要があります。
Vue.component('click-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count += 1">{{ count }}</button>'
})