vue组件非常常见的有父子组件通信,兄弟组件通信。而父子组件通信就很简单,父组件会通过 props
向下传数据给子组件,当子组件有事情要告诉父组件时会通过 $emit
事件告诉父组件。今天就来说说如果两个页面没有任何引入和被引入关系,该如何通信了?
eventBus 又称为事件总线。在 Vue 中可使用 eventBus 来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可向该中心注册发送事件或接收事件,所以组件都可以上下平行地通知其他组件。但也就是太方便所以若使用不慎,就会造成难以维护的“灾难”,因此才需要更完善的 Vuex 作为状态管理中心,将通知的概念上升到共享状态层次。
安装及引入
npm install vue-bus --save
如果在一个模块化工程中使用它,必须要通过 Vue.use() 明确地安装 vue-bus:
// main.js
import Vue from 'vue';
import VueBus from 'vue-bus';
Vue.use(VueBus);
在组件中使用
假设有两个Vue组件需要通信 ,在 A 组件的按钮上面绑定了点击事件发送一则消息,想通知 B 组件。
// A 组件
<template>
<div class="wrap">
<button @click="sendMsg">触发</button>
</div>
</template>
<script>
export default {
data(){
return {
Amsg:'我是来自A组件的信息',
}
},
methods:{
sendMsg(){
this.$bus.emit('changeMsg', this.Amsg );
this.$bus.emit('doOnce','我只会触发一次');
}
},
}
</script>
// B 组件
<template>
<div>
<h3>{{Bmsg}}</h3>
</div>
</template>
<script>
export default {
data(){
return {
Bmsg:'我是B组件',
}
},
methods:{
getMsg(msg){
this.Bmsg = msg;
console.log(msg);
}
},
created(){
/*
* 接收事件
* 这种写法也体现了:A 组件调用 B 组件中的方法。如果只是传递数据,可参考如下简化写法:
* this.$bus.on('changeMsg', (msg) => { this.Bmsg = msg });
*/
this.$bus.on('changeMsg', this.getMsg);
// 此侦听器只会触发一次
this.$bus.once('doOnce', (txt) => { console.log(txt) });
},
// 组件销毁时,移除EventBus事件监听
beforeDestroy() {
this.$bus.off('changeMsg', this.addTodo);
},
}
</script>