非父子間傳值聲明一個(gè)第三方量來(lái)傳值
效果圖:
QQ截圖20180922101550.png
點(diǎn)擊后:
QQ截圖20180922101634.png
body:
<div id='app'>
<child></child>
<son></son>
</div>
js:
<script>
//第三方量bus
var bus=new Vue()
//第一個(gè)組件
Vue.component('child',{
template:`
<div>
<h1>這是組件A</h1>
<button @click='sendMsg'>點(diǎn)擊按鈕傳值</button>
</div>
`,
data:function(){
return{
msg:'非父子組件傳值'
}
},
methods:{
sendMsg:function(){
bus.$emit('send',this.msg)
}
}
})
//第二個(gè)組件
Vue.component('son',{
template:`
<div>
<h1>這是組件B</h1>
<a href="#">{{mess}}</a>
</div>
`,
data:function(){
return{
mess:''
}
},
mounted:function(){
bus.$on('send',msg=>{
console.log(this);
this.mess=msg;
})
}
})
new Vue({
el:'#app'
})
</script>