背景
主页面 需要加载两个不同的组件,并且在点击 A 组件的时候,B组件中的内容会对应的改变。
使用
component1 点击触发事件,再component2 中监听并进行后续操作。
首先,在main.js中添加
Vue.prototype.msgCenter = new Vue()
主页面 component1 和 component2 是兄弟关系
<template>
<div>
<component1 />
<component2 />
</div>
</template>
component1 中 发送:
<template>
<div @click="sendMsg">
</div>
</template>
<script>
export default {
name: "",
data: function () {
return {};
},
computed: {},
methods:{
sendMsg() {
this.msgCenter.$emit("componentSend",{msg:"value", msg2: "value2"})
// 通过再main.js 里面添加的 msgCenter 发送
// emit 的第一个参数是 事件名称,第二个参数是 需要发送的数据
},
}
};
</script>
component2
<script>
export default {
name: "",
data: function () {
return {};
},
computed: {},
methods: {
//监听到事件后触发
// 默认参数 val 就是在component1 emit 过来的数据
receiveMsg(val) {
console.log(val)
// 打印数据 {msg:"value", msg2: "value2"}
}
},
created() {
//在created 中 on 监听
// on 的第一个参数是事件名称,第二个参数是 监听到事件后对应触发的方法
this.msgCenter.$on("componentSend", this.receiveMsg);
},
beforeDestroy() {
// 销毁,否则可能会导致多次触发 on
this.msgCenter.$off("componentSend");
},
};
</script>
总结
实际上就是 eventBus 的机制。
具体流程就是:
- 在 main.js 中注册好msgCenter
- 在发送数据的组件中通过 emit 发出并且确定好对应的事件名称和参数
- 在需要接受的组件中通过 on 监听对应的事件,并且制定处理函数。处理函数的默认参数就是 emit 传递过来的数据。
- 在接受的组件中销毁对应的 on 监听。
本文详细介绍了如何在Vue应用中使用EventBus实现组件间的通信。通过创建一个全局的Vue实例作为消息中心,组件1可以发送事件和数据,而组件2则监听并响应这些事件,实现内容的动态更新。这种通信方式适用于兄弟组件或其他非父子组件之间的数据传递,是一种常见的Vue开发技巧。
963

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



