knowLedge-无关系组件间方法的调用(创建新的 Vue 实例来作为事件总线(Event Bus)方法实现)

1.前言

在vue中两个组件无关系(非父子,兄弟即非直接关系),要实现一个组件对另一个组件方法调用以及数据通信。vue本身没有直接提供非关系组件间通信的内置机制 。

使用全局事件总线可以用于不同组件间监听与触发事件。注意事件监听器的清理避免内存泄露。

2.实践

2.1创建event-bus.js

首先,创建一个单独的 Vue 实例文件(比如 event-bus.js),这个文件将作为事件总线:

javascript 复制代码
// event-bus.js  
import Vue from 'vue';  
export const EventBus = new Vue();

在需要触发和监听的事件对应的组件中引入,根据需求进行调整修改。

2.2 组件A触发事件

使用 $emit 来触发事件。

javascript 复制代码
<!-- ComponentA.vue -->  
<template>  
  <button @click="triggerEvent">Trigger Event in Component B</button>  
</template>  
  
<script>  
import { EventBus } from './event-bus.js';  
  
export default {  
  methods: {  
    triggerEvent() {  
      // 使用事件总线触发事件  
      EventBus.$emit('custom-event', { message: 'Hello from Component A' });  
    }  
  }  
}  
</script>
2.3组件B监听事件

使用 $on 来监听事件。

javascript 复制代码
<!-- ComponentB.vue -->  
<template>  
  <div>  
    <p>Message from Component A: {{ message }}</p>  
  </div>  
</template>  
  
<script>  
import { EventBus } from './event-bus.js';  
  
export default {  
  data() {  
    return {  
      message: ''  
    };  
  },  
  created() {  
    // 组件创建时监听事件  
    EventBus.$on('custom-event', (data) => {  
      this.message = data.message;  
    });  
  },  
  beforeDestroy() {  
    // 组件销毁前移除监听器,防止内存泄漏  
    EventBus.$off('custom-event');  
  }  
}  
</script>

3.总结

ComponentA 使用 EventBus.$emit 来触发一个名为 custom-event 的事件,并传递了一个包含消息的对象作为参数。ComponentB 则在 created 钩子中使用 EventBus.$on 来监听这个事件,并在事件触发时更新其 message 数据属性。

相关推荐
sunny_1 分钟前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
前端·rust·前端工程化
rfidunion1 小时前
springboot+VUE+部署(12。Nginx和前端配置遇到的问题)
前端·vue.js·spring boot
vx-Biye_Design1 小时前
servlet家政公司管理系统-计算机毕业设计源码01438
java·vue.js·spring·servlet·tomcat·maven·mybatis
珹洺1 小时前
Java-servlet(五)手把手教你利用Servlet配置HTML请求与相应
java·运维·服务器·前端·servlet·html·maven
FYKJ_20101 小时前
springboot大学校园论坛管理系统--附源码42669
java·javascript·spring boot·python·spark·django·php
QQ24391971 小时前
语言在线考试与学习交流网页平台信息管理系统源码-SpringBoot后端+Vue前端+MySQL【可直接运行】
前端·spring boot·sql·学习·java-ee
范特西.i2 小时前
QT聊天项目(6)
前端
a1117762 小时前
水体渲染系统(html开源)
前端·开源·threejs·水体渲染
程序员小李白2 小时前
CSS 盒子模型
前端·css·html
Zzz不能停3 小时前
单行 / 多行文本显示省略号(CSS 实现)
前端·css