一、在Vue 的原型中创建一个属性 bus
Vue.prototype.bus=new Vue();
二、子组件中绑定事件 比如叫 handleClick,在子组件中定义 hanleClick 方法 ,handleClick 方法中使用
this.bus.$emit('change',this.contentmsg); 触发事件 ‘ change ’ ,携带this.contentmsg 。
三,使用mouted 钩子函数监听 bus 的改变。
mounted:function(){
var this_=this;
this.bus.$on('change',function(msg){
this_.contentmsg=msg;
})
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>非父子之间的传值 bus / 总线 </title>
</head>
<body>
<div id="root">
<child content="Dell"></child>
<child content="Lee"></child>
</div>
<script src="vue.js"></script>
<script>
Vue.prototype.bus=new Vue();
Vue.component('child',{
props:{
content:{
type:String
}
},
data:function(){
return {
contentmsg:this.content
}
},
template:'<div @click="handleClick" >{{contentmsg}}</div>',
methods: {
handleClick : function(){
this.bus.$emit('change',this.contentmsg);
}
},
mounted:function(){
var this_=this;
this.bus.$on('change',function(msg){
this_.contentmsg=msg;
})
}
});
var vm = new Vue({
el:'#root',
});
</script>
</body>
</html>