Vue 中非父子组件间的传值
栏目: JavaScript · 发布时间: 7年前
内容简介:非父子之间传值,可以采用组件被挂载之前会执行
总线机制
非父子之间传值,可以采用 发布订阅模式
,这种模式在 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()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Building Social Web Applications
Gavin Bell / O'Reilly Media / 2009-10-1 / USD 34.99
Building a social web application that attracts and retains regular visitors, and gets them to interact, isn't easy to do. This book walks you through the tough questions you'll face if you're to crea......一起来看看 《Building Social Web Applications》 这本书的介绍吧!