非父子間的傳值也可以理解為同級(jí)之間的傳值
在非父子傳值中主要聲明了一個(gè):
var 變量 = new Vue();
指向Vue實(shí)例的變量.
其次
使用 $emit("發(fā)送的數(shù)據(jù)名",數(shù)據(jù)內(nèi)容) 來(lái)發(fā)送數(shù)據(jù)
使用 $on("接收的數(shù)據(jù)名",使用箭頭函數(shù)指向本組件的數(shù)據(jù))
案例
<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'>發(fā)送數(shù)據(jù)</button>
</div>
`,
data:function(){
return{
msg:'我是child組件中的數(shù)據(jù)虾宇,要傳給son組件'
}
},
methods:{
sendMsg:function(){//發(fā)送數(shù)據(jù)
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=>{//接收數(shù)據(jù)杂穷,使用箭頭函數(shù)指向這個(gè)組件本身的數(shù)據(jù)
console.log(this);
this.mess=msg
})
}
})
new Vue({
el:'#app'
})
</script>
QQ截圖20180923200808.png