組件通信
1:父?jìng)髯樱?br> 父?jìng)髯?- 在組件標(biāo)簽上通過(guò)自定義屬性的形式:list="list1"綁定數(shù)據(jù)值漫,然后在子組件中通過(guò)props接收props:["list"]
// 組件標(biāo)簽 - 父組件
<custom-select :list="list1"></custom-select>
// 子組件接收
props: [ 'list' ],
2:子傳父
在子組件中通過(guò)this.$emit('自定義事件名稱', '要傳遞的數(shù)據(jù)'),完成子組件配置
在子組件的組件標(biāo)簽上通過(guò)@自定義事件名稱="事件處理函數(shù)"芦疏,來(lái)完成父組件接收的任務(wù)
// 子組件 - 發(fā)布
this.$emit('receive', val) // 第一個(gè)參數(shù):“自定義事件名稱”;第二個(gè)參數(shù):你要傳遞的數(shù)據(jù)
// 父組件 - 接收
<list @receive="changeVal"></list>
3: 兄弟通信
目前中央通信是解決組件通信的最佳方法。
無(wú)需關(guān)注組件嵌套層級(jí),也無(wú)需關(guān)注組件關(guān)系肩钠、
on - 監(jiān)聽(tīng)訂閱
let bus = new Vue() // 空實(shí)例
// 組件A
Vue.component('Aaa', {
template: `我是A組件`,
methods: {
aaa() {
bus.$emit('is-selected')
}
}
});
// 組件B
Vue.component('Bbb', {
template: `我是B組件`,
created() {
bus.$on('is-selected', function () {
console.log('我是B組件');
})
}
});
//Vue實(shí)例
new Vue({
el: '#app'
})