非父子之间的通信
先声明一个中间值
var bus= new Vue
发送方用$emit()
接收方用$on()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<child></child>
<son></son>
</div>
<script src='js/vue.js'></script>
<script>
var bus=new Vue();
Vue.component('child',{//a
template:`
<div>
<h2>我是child组件</h2>
<button @click='sendMsg'>发送数据</button>
</div>
`,
data:function(){
return{
msg:'我是child组件中的数据,要传给son组件'
}
},
methods:{
sendMsg:function(){//发送数据
bus.$emit('send',this.msg)
}
}
})
Vue.component('son',{//b
template:`
<div>
<h2>我是son组件</h2>
<a>{{mess}}</a>
</div>
`,
data:function(){
return{
mess:''
}
},
mounted:function(){
bus.$on('send',msg=>{
console.log(this);
this.mess=msg
})
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>