Vue 中非父子组件间的传值

总线机制
非父子之间传值,可以采用发布订阅模式,这种模式在 Vue 中被称为总线机制,或者叫做Bus / 发布订阅模式 / 观察者模式
<div id=”root”>
<child content=”Dell”></child>
<child content=”Lee”></child>
</div>

Vue.prototype.bus = new Vue() //挂载 bus 属性

Vue.component(‘child’, {
data(){
return {
selfContent: this.content
}
},
props: {
content:String
},
template: ‘<div @click=”handleChildClick”>{{selfContent}}</div>’,
methods: {
handleChildClick() {
this.bus.$emit(‘change’,this.selfContent) // 发布
}
},
mounted(){
this.bus.$on(‘change’,(msg)=>{ //订阅,这里会被执行两次
this.selfContent = msg
})
}
})

let vm = new Vue({
el: ‘#root’
})
Vue.prototype.bus = new Vue()这句话的意思是,在 Vue 的prototype挂载了一个bus属性,这个属性指向 Vue 的实例,只要我们之后调用 Vue 或者new Vue时,每个组件都会有一个bus属性,因为以后不管是 Vue 的属性还是 Vue 的实例,都是通过 Vue 来创建的,而我在 Vue 的prototype上挂载了一个bus的属性。
组件被挂载之前会执行mounted钩子函数,所以可以在mounted中对change事件进行监听。
this.bus.$on()那边会被执行两次,原因是什么呢?因为在一个child组件里面,触发事件的时候,外面两个child的组件都进行了同一个事件的监听,所以两个child的组件都会执行一遍this.bus.$on()

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理