組件 (Component) 是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自定義元素,Vue.js 的編譯器為它添加特殊功能。在有些情況下,組件也可以表現(xiàn)為用 is 特性進行了擴展的原生 HTML 元素。
所有的 Vue 組件同時也都是 Vue 的實例,所以可接受相同的選項對象 (除了一些根級特有的選項) 并提供相同的生命周期鉤子。
注冊一個全局組件,可以使用Vue.component(tagName, options)
Vue.component('my-component', {
// 選項
})
組件在注冊之后,便可以作為自定義元素 <my-component></my-component>在一個實例的模板中使用。注意確保在初始化根實例之前注冊組件
// 注冊
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
// 創(chuàng)建根實例
new Vue({
el: '#example'
})
如此長篇大論copy自Vue API
<div id="app">
<my-test></my-test>
</div>
<script src="vue.js"></script>
<script>
// 1.創(chuàng)建組件構(gòu)造器
let Profile = Vue.extend({
// 1.1 模板選項
template:`
<div>
<p>測試</p>
</div>
`
});
// 2.注冊一個全局的組件
Vue.component('my-test',Profile);
new Vue({
el: '#app',
});
</script>
和
<div id="app">
<my-test></my-test>
</div>
<script src="vue.js"></script>
<script>
Vue.component('my-test',{
template:`
<div>
<p>測試</p>
</div>
`
});
new Vue({
el: '#app',
});
</script>
作用一致
父子組件
<div id="app">
<parent></parent>
</div>
<script src="js/vue.js"></script>
<script>
// 1.子組件構(gòu)造器
// 若要使用這些組件,需要在外面重新注冊
let Child1 = Vue.extend({
template: `<img src="img_01.png" width="340">`
});
let Child2 = Vue.extend({
template: `<p>啦啦啦</p>`
});
// 2.父組件構(gòu)造器
Vue.component('parent',{
components: {
'my-child1': Child1,
'my-child2': Child2
},
template:
`
<div>
<my-child1></my-child1>
<my-child2></my-child2>
</div>
`
});
new Vue({
el: '#app'
});
</script>

掛載選項
data必須是函數(shù)
構(gòu)造 Vue 實例時傳入的各種選項大多數(shù)都可以在組件里使用。只有一個例外:data 必須是函數(shù)
Vue.component('my-component', {
template: '<span>{{ message }}</span>',
data: {
message: 'hello'
}
})
那么 Vue 會停止運行,并在控制臺發(fā)出警告,只有data為函數(shù)才能用
示例:
<div id="app">
<my-div></my-div>
</div>
<script id="my-div" type="test/template">
<div>
<p>說你是豬!</p>
<input type="text" placeholder="說你是豬">
<p>{{msg}}</p>
</div>
</script>
<script src="js/vue.js"></script>
<script>
Vue.component('my-div',{
template: '#my-div',
data(){
return {
msg: '哈哈哈哈!'
}
}
});
new Vue({
el: '#app'
});
</script>