运用事件总线的方式来完成组件间的通信(不用考虑组件之间的关系)传递参数
三步搞定
1.在mian.js 中定义事件总线 $bus (让载体拥有Vue实例上的 $on, $off, $emit方法); ==> Vue.prototype.$bus = this; // 安装事件总线
import Vue from 'vue';
import App from './app'
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this; // 安装事件总线
}
}).$mount('#app');
2.兄弟组件demo2 接收来自兄弟组件 demo1 的值
首先demo2 自定义事件接收来自demo1的参数
export default {
name: "Demo2",
data() {
return {
};
},
mounted() {
// 这里是兄弟组件 demo2
this.$bus.$on('getDemo1Value', (...params) => {
console.log(params, '来自兄弟demo1的值')
});
},
};
demo1 发出事件并传递参数 ==> this.$bus.$emit(“getDemo1Value”, this.msg);
<template>
<div><button @click="sendTodemo2">sendTodemo2</button></div>
</template>
<script>
export default {
name: "Demo1",
data() {
return {
msg: "数据1_demo1"}},
methods: {
sendTodemo2() {
this.$bus.$emit("getDemo1Value", this.msg);
}
}
};
</script>
最后打开控制台完成兄弟数据传递(父子,子父,兄弟关系用法相同);
说一个小点
在销毁某个自定义事件的组件后 建议在组件beforeCreate生命周期内解绑事件
beforeCreate() {
this.$bus.$off('getDemo1Value');
}