在vue兄弟之间的数据传递,通过事件车(eventBus)发布订阅实现
vm.$on( event, callback )
$on中有两个参数,一个event(事件名),一个callback(回调函数,this指向window)
vm.$emit( event, val )
$emit中有两个参数,一个event(事件名),一个val(需要传递的值)
let eventBus = new Vue; //事件车,用来连接两个兄弟 let brother1 = { template:`<div>{{color}}<button @click="change">变绿</button></div>`, data(){ return{ color:"绿色", old:"绿色" } }, methods:{ change(){ eventBus.$emit("changeGreen",this.old) } }, created(){ eventBus.$on("changeRed",(val)=>{this.color=val}) } }; let brother2 = { template:`<div>{{color}}<button @click="changes">变红</button></div>`, data(){ return{ color:"红色", old:"红色" } }, methods:{ changes(){ eventBus.$emit("changeRed",this.old) } }, created(){ eventBus.$on("changeGreen",(val)=>{this.color=val}) } }; new Vue({ el:"#app", components:{ brother1, brother2 } })