◆ 組件:
組件 (Component) 是 Vue.js 最強大的功能之一,組件可以擴展 HTML 元素,封裝後可以進行重用。
◆ 組件註冊:
1、全局註冊:
全局組件註冊後,任何vue實例都可以用
Vue.component('組件名稱', { })
第1個參數是標籤名稱,第2個參數是一個選項對象
<div id="example">
<!-- 組件使用 組件名稱 是以HTML標籤的形式使用 -->
<my-component></my-component>
</div>
<script>
// 註冊組件
// my-component 就是組件中自定義的標籤名
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
// 創建根實例
new Vue({
el: '#example'
})
</script>
組件注意事項:
- 組件參數的data值必須是函數同時這個函數要求返回一個對象
- 組件模板必須是單個根元素
- 組件模板的內容可以是模板字符串
<div id="app">
<!--
4、 組件可以重複使用多次
因爲data中返回的是一個對象所以每個組件中的數據是私有的
即每個實例可以維護一份被返回對象的獨立的拷貝
-->
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
<!-- 8、必須使用短橫線的方式使用組件 -->
<hello-world></hello-world>
</div>
<script type="text/javascript">
//5 如果使用駝峯式命名組件,那麼在使用組件的時候,只能在字符串模板中用駝峯的方式使用組件,
// 7、但是在普通的標籤模板中,必須使用短橫線的方式使用組件
Vue.component('HelloWorld', {
data: function(){
return {
msg: 'HelloWorld'
}
},
template: '<div>{{msg}}</div>'
});
Vue.component('button-counter', {
// 1、組件參數的data值必須是函數
// 同時這個函數要求返回一個對象
data: function(){
return {
count: 0
}
},
// 2、組件模板必須是單個根元素
// 3、組件模板的內容可以是模板字符串
template: `
<div>
<button @click="handle">點擊了{{count}}次</button>
<button>測試123</button>
# 6 在字符串模板中可以使用駝峯的方式使用組件
<HelloWorld></HelloWorld>
</div>
`,
methods: {
handle: function(){
this.count += 2;
}
}
})
var vm = new Vue({
el: '#app',
data: {
}
});
</script>
2、局部註冊:
局部註冊只能在當前註冊它的vue實例中使用
<div id="app">
<my-component></my-component>
</div>
<script>
// 定義組件的模板
var Child = {
template: '<div>A custom component!</div>'
}
new Vue({
//局部註冊組件
components: {
// <my-component> 將只在父模板可用 一定要在實例上註冊了才能在html文件中使用
'my-component': Child
}
})
</script>