コンポーネント
templateのなかにHTML書く
Vue.js
Vue.component('button-preference', {
data() {
return { count: 0 };
},
methods: {
countUp() {
this.count += 1;
},
},
template: `
<button v-on:click="countUp">
{{ count }} いいね!
</button>
`,
});
new Vue({
el: '#example',
});
グローバル登録
Vue.js
Vue.component('button-preference', {
template: `
<button>いいね!</button>
`
});
Vue.component('button-empathy', {
template: `
<button>そだねー</button>
`,
});
Vue.component('buttons-sns', {
template: `
<div>
<button-preference></button-preference>
<button-empathy></button-empathy>
</div>
`,
});
new Vue({
el: '#example',
});
#ローカル登録
ローカル登録するにはまず、コンポーネントをオブジェクトとして定義します。
プロパティ名はクォーテーションで囲ってください。
components
プロパティーを使う
Vue.js
const buttonPreference = {
template: `
<button>いいね!</button>
`,
};
const buttonEmpathy = {
template: `
<button>そだねー</button>
`,
};
//上の二つのコンポーネントをしたで使う
const buttonsSns = {
components: {
'button-preference': buttonPreference,
'button-empathy': buttonEmpathy,
},
template: `
<div>
<button-preference></button-preference>
<button-empathy></button-empathy>
</div>
`,
};
上記のbuttonsSnsコンポーネントをVueインスタンスで使う↓
vue.js
new Vue({
el: '#example',
components: {
'buttons-sns': buttonsSns,
},
});
一部省略
<!DOCTYPE html>
<body>
<div id="example">
<buttons-sns></buttons-sns>
</div>
</body>
</html>
親から子にデータを渡す
new Vue{{...}}
== 親
butoon-sns
== 子
vue.js
new Vue({
el: '#example',
components: {
'buttons-sns': buttonsSns,
},
});
props
を使ってデータ渡す
このデータには、dataオプションのデータと同じようにアクセスできます。
つまり、 this.ooo
でアクセス??? (定かではない)
vue.js
const buttonPreference = {
props: ['initialCount'],
template: `
<button>
{{ initialCount }} いいね!
</button>
`,
};
new Vue({
el: '#example',
components: {
'button-preference': buttonPreference,
},
});
<body>
<div id="example">
<button-preference initial-count="0"></button-preference>
</div>
<script src="main.js"></script>
</body>
</html>
補足:名前のつけ方
javascriptではキャメルケース
(initialCount )
テンプレート(HTML)ではケバブケース
(initial-count)
props
props: ['count', 'counts', 'value'],
と複数指定可能
props: {
count: {
type: Number,
required: true,
},
counts: {
type: Array,
required: true,
},
},
↑とpropsのルール指定可能
公式 https://jp.vuejs.org/v2/guide/components-props.html#%E3%83%97%E3%83%AD%E3%83%91%E3%83%86%E3%82%A3%E3%81%AE%E3%83%90%E3%83%AA%E3%83%87%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3
EXAMPLE
vue.js
const buttonPreference = {
props: {
initialCount: {
type: Number,
required: true,
},
},
template: `
<button>
{{ initialCount }} いいね!
</button>
`,
};
new Vue({
el: '#example',
components: {
'button-preference': buttonPreference,
},
});
<div id="example">
<button-preference initial-count="0"></button-preference>
</div>
initial-count='0'
でエラー(文字列だから)
解決方法
<div id="example">
<button-preference v-bind:initial-count="0"></button-preference>
</div>
v-bindを使う