非父子组件(隔多代、兄弟等)之间传值,主要有两种方式:
- vuex
- 发布订阅模式(在 vue 中称为总线机制)
下文将介绍通过总线机制(Bus/总线/发布订阅模式/观察者模式),解决非父子组件之间的传值。
<div id="root">
<child content="Hello"></child>
<child content="You"></child>
</div>
<script>
// 使得每一个Vue 实例都有一个bus属性 ,该属性指向同一个实例
Vue.prototype.bus = new Vue();
Vue.component('child',{
data: function(){
return {
selfContent: this.content
}
},
props: {
content: String
},
template: "<div @click='handleClick'>{{selfContent}}</div>",
methods: {
handleClick: function(){
this.bus.$emit('change',this.selfContent);
}
},
// 生命周期函数,被挂载的时候触发
mounted: function(){
var this_ = this
this.bus.$on('change',function(msg){
this_.selfContent = msg;
})
}
})
var vm = new Vue({
el: "#root"
})
</script>
其中,emit 与 on 是vue 提供的方法:
vm.$emit('msg',this.msg); 发送数据,第一个参数是发送数据的名称,接收时还用这个名字接收,第二个参数是接收端接收到的参数;
vm.$on('msg',function(msg){ 接收数据,第一个参数是数据的名字,与发送时的名字对应,第二个参数是一个方法,要对数据的操作。