Vue兄弟组件之间的数据传递 可以用过一个vue实例Bus作为媒介,要相互通信的兄弟组件之中,都引入Bus,之后通过分别调用Bus事件触发on来实现组件之间的通信和参数传递
eventBus.js
import Vue from 'vue';
export default new Vue;
----------------------------------------
ChildOne.vue
<template>
<div>
<p>child 1 {{name}}</p>
<button @click="handleClick">点击</button>
</div>
</template>
<script>
import bus from '../eventBus';
export default {
name: 'ChildOne',
data(){
return{
name:"我是老大-----ChildOne",
}
},
methods: {
handleClick() {
//子组件1 通过 bus.$emit()绑定自定义事件
bus.$emit("sendBrother",this.name)
}
},
}
</script>
------------------------------------------
ChildTwo.vue
<template>
<div>
<p>child 2 {{name}} </p>
</div>
</template>
<script>
import bus from '../eventBus';
export default {
name: 'ChildTwo',
data(){
return{
name:"我是老二-----ChildTwo",
}
},
mounted() {
//子组件2通过bus.$on('参数1','参数2'); 参数1是接收的自定义事件,参数2是一个回调函数
bus.$on("sendBrother",(e)=>{
this.name=e
})
},
}
</script>