全局組件VS局部組件
- 全局組件
全局可調(diào)用,可在一個或多個掛在了Vue實(shí)例的DOM節(jié)點(diǎn)內(nèi)使用該組件其馏。
<body>
<div id="app1">
<my-component></my-component>
</div>
<div id="app2">
<my-component></my-component>
</div>
<!-- js -->
<script>
Vue.component("my-component",{
template:`<div>我是全局組件</div>`
})
new Vue({
el:'#app1',
})
new Vue({
el:'#app2'
})
</script>
</body>
- 局部組件
在Vue實(shí)例內(nèi)聲明的組件凤跑,只能在該實(shí)例內(nèi)調(diào)用,局部組件和全局組件同時存在(組件名相同)時尝偎,局部組件會覆蓋全局組件饶火。
<body>
<div id="app">
<my-component></my-component>
</div>
<!-- js -->
<script>
new Vue({
el:'#app',
components:{
'my-component':{
template:`<div>我是局部組件</div>`,
}
}
})
</script>
</body>
組件間通信方案
通過props傳遞
$emit觸發(fā)自定義事件
使用 ref
總線,EventBus
parent/root
attrs 與 listeners
Provide 與 Inject
Vuex
父->子
父組件通過屬性賦值的方式向子組件傳值致扯,子組件通過
props
接收,使用肤寝。
<body>
<div id="app">
<my-component :title="title"></my-component>
</div>
<!-- js -->
<script>
Vue.component("my-component",{
template:`<div @click='cont++'>{{cont}}</div>`,
data(){ //子組件的data必須是函數(shù)
return{
cont:this.title, //將接收的值暫存
}
},
props:{
title:{
type: Number, //傳過來的值必須是Number類型
default:0,
required:true //傳值不能為空
}
}
})
new Vue({
el:'#app',
data(){
return{
title:0 //父組件綁定傳值
}
},
})
</script>
</body>
子->父
子組件通過向外觸發(fā)方法的方式向父組件傳值。
<body>
<div id="app">
{{total}}
<my-component @addtotal="add"></my-component>
<my-component v-on:addtotal="add"></my-component>
</div>
<!-- js -->
<script>
Vue.component("my-component",{
template:`<div @click='addCont'>{{cont}}</div>`,
data(){
return{
cont:0
}
},
methods:{
addCont(){
this.cont++;
this.$emit("addtotal");//子組件通過$emit向上觸發(fā)方法
}
},
})
new Vue({
el:'#app',
data(){
return{
total:0,
}
},
methods:{
add(){
this.total++;
}
}
})
</script>
</body>
ref
父組件獲取子組件實(shí)例抖僵,調(diào)用子組件方法鲤看、獲取子組件數(shù)據(jù)
// 子組件
<Children ref='son'></Children>
this.$refs.son // 子組件實(shí)例,可繼續(xù) . 拿到對應(yīng)數(shù)據(jù)
EventBus
適用于:兄弟組件耍群、無關(guān)系組件
// 創(chuàng)建總線(vue 已經(jīng)實(shí)現(xiàn)了Bus)
class Bus {
constructor(){
this.callbacks = {}; // 存放事件的名字
}
$on(name,fn){
this.callbacks[name] = this.callbacks[name] || [];
this.callbacks[name].push(fn);
}
$emit(name,args){
if(this.callbacks[name]){
this.callbacks[name].forEach(cb => cb(args));
}
}
}
// main.js (掛在在vue實(shí)例的原形上)
Vue.prototype.$bus = new Bus();
// 未完……