1、bus总线中央发布令
如图所示,加入组件:1–3需要进行数据传递,一般情况下会通过组件2作为中间者,进行传值;但如果组件:3–3也需要通信,这时候再通过3向上传,一层一层是非常复杂的;vue是一个轻量级的框架,遇到复杂的数据处理时,需要借助其他工具;
这里我们使用 bus 总线(中央发布令)
代码示例:已下代码中列举了两种组件之间通过change事件进行通信;
首先将bus挂载到vue实例中
Vue.prototype.bus = new Vue();
//组件一:
Vue.component('one',{
props:{
temContent:String
},
data:function () {
return{
content:this.temContent
}
},
template:`<div>
<p @click="handleClick">{{content}}</p>
</div>`,
methods:{
handleClick:function () {
this.bus.$emit('change',this.content);
this.bus.$emit('samechange',this.content)
},
},
mounted:function () {
var self = this;
this.bus.$on('change',function (msg) {
//do something
self.content = msg
});
this.bus.$on('samechange',function (msg) {
//do somthing
})
}
});
//组件二
Vue.component('two', {template:`<div @click="handleClick"><div>{{content}}</div></div>`,
props:{
tempContent:{
type:String,
}
},
data:function(){
return{
content:this.tempContent
}
},
methods:{
handleClick:function(){
//do somthing
this.bus.$emit('change',this.tempContent)
}
},
mounted:function () {
var self = this;
this.bus.$on('change',function (msg) {
//do somthing
self.tempContent = msg
})
}
});