Vue事件总线
事件总线是一种,它的功能比较强大,不局限于父传子之间通信,它可以在兄弟之间通信和跨组件通信,通过事件总线传递回调函数引用,来达到传递值的目的。
使用步骤
- 在Vue中定义一个全局变量作为事件总线。
- 在接收参数的VC中 定义事件函数。
- 在发送参数的VC中定义触发事件的函数。
参考示例
目的:使School与Student兄弟组件之间通信。
在main.js创建Vue实例时绑定事件总线在Vue上,这样创建的VueComponent都能访问到。
在Student中定义事件,在School中调用事件,达到兄弟组件通讯的目的。
main.js
import Vue from "vue"
import App from "./App"
Vue.config.productionTip = false;
new Vue({
el: "#app",
render: h => h(App),
//Vue创建之前绑定事件总线
beforeCreate() {
Vue.prototype.$bus = this;
}
})
App.vue
<template>
<div>
<School/>
<Student/>
</div>
</template>
<script>
import Student from "./components/Student.vue";
import School from "./components/School.vue";
export default {
name: "App",
components: {
Student,
School
},
data() {
return {
name: "希望",
};
},
methods: {
},
};
</script>
student.vue
<template>
<div>
</div>
</template>
<script>
export default {
name: "Student",
//在事件总线中绑定事件函数
mounted() {
this.$bus.$on("hello", (data) => {
console.log("student receive ", data);
});
},
//销毁前解绑定义的事件
beforeDestroy() {
this.$bus.$off("hello");
},
};
</script>
school.vue
<template>
<div>
<button @click="clickEvent">School的按钮</button>
</div>
</template>
<script>
export default {
name: "School",
methods: {
clickEvent(){
this.$bus.$emit("hello","李义新");
}
},
};
</script>
消息订阅与发布
- 消息订阅与发布的实现需要用到第三方库:pubsub-js。
- 终端使用npm i pubsub-js进行安装。
- 引入:import pubsub from "pubsub-js"。
- 发布订阅
- 可以放到点击事件中
clickEvent() { pubsub.publish("hello",666); },
- 可以放到点击事件中
- 订阅消息与取消订阅消息
- 订阅消息(一般在mounted函数中)
mounted(){ //使用箭头函数this是VC //只有使用接收订阅函数返回的id,才能关闭订阅 //messageName是订阅的名称,data是发送订阅 发出的信息 this.pubId = pubsub.subscribe("hello", (messageName, data) => { console.log("School receive message: ", messageName, " ", data); }); }
- 取消订阅消息(一般在beforeDestory函数中)f
beforeDestroy() { pubsub.unsubscribe(this.pubId); }
- 订阅消息(一般在mounted函数中)