-
首先在main.js文件下添加:
//main.js
Vue.prototype.$EventBus = new Vue()
-
在左侧的组件,比如是组件Left,当中触发事件。
// Left.vue
<template>
<div>
<button @click="sendMsg"><button>
</div>
</template>
<script >
export default {
data() {
return {}
},
methods: {
sendMsg() {
this.$EventBus.$emit("send", "这里是数据");
}
}
}
</script>
-
在右侧的组件当中,Right组件,将事件挂载到组件上,然后等待该事件被触发。
//Right.vue
mounted() {
this.$EventBus.$on("send", (data) => {
alert(data);
})
},
// 注意要在组件销毁之前把事件解绑
beforeDestory() {
this.$EventBus.$off("send");
}
文章介绍了在Vue项目中,如何通过在main.js中创建一个全局的$EventBus实例来实现组件间的通信。在Left组件中触发事件,Right组件监听并响应这个事件,接收到数据后进行相应操作。同时强调了在组件销毁前需要解除事件绑定以防止内存泄漏。

2737

被折叠的 条评论
为什么被折叠?



