Vue 中非父子组件间的传值

0次阅读

共计 832 个字符,预计需要花费 3 分钟才能阅读完成。

总线机制
非父子之间传值,可以采用发布订阅模式,这种模式在 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()

正文完
 0