Vue —— 使用EventBus处理组件之间的数据通信

本文介绍了如何在Vue应用中使用EventBus作为组件间通信的桥梁,以替代Vuex。通过创建一个全局的Vue实例,组件可以方便地发送和监听事件。然而,这种便利也可能导致代码难以维护,因此在需要更复杂状态管理时,推荐使用Vuex。文中提供了一个具体的案例,展示了在index.vue和childCom.vue中如何使用EventBus进行事件触发和响应,包括数据获取、事件监听和组件间的交互操作。

如果咱们的应用程序不需要类似Vuex这样的库来处理组件之间的数据通信,就可以考虑Vue中的 事件总线 ,即 EventBus来通信。

EventBus的简介

EventBus 又称为事件总线。在Vue中可以使用 EventBus 来作为沟通桥梁的概念,就像是所有组件共用相同的事件中心,可以向该中心注册发送事件或接收事件,所以组件都可以上下平行地通知其他组件,但也就是太方便所以若使用不慎,就会造成难以维护的“灾难”,因此才需要更完善的Vuex作为状态管理中心,将通知的概念上升到共享状态层次。

案例:

/src/util/eventBus.js

import Vue from "vue";

export default new Vue();

index.vue:

<template>
  <div class="linkorigin-wrapper">
    <Breadcrumbs />
    <div class="content-wrapper">
      <TabList @tabEvent="tabEvent($event)" :type="type" :tabList="tabList">
        <template v-slot:action-buttons v-if="tabId === 1">
          <v-btn
            depressed
            color="primary"
            @click.stop="$refs.component.doCreate()"
            style="margin-right:20px"
            >新增</v-btn
          >
          <v-btn
            depressed
            color="primary"
            @click.stop="$refs.component.saveMapping()"
            >保存</v-btn
          >
        </template>
      </TabList>
      <component :is="curCom" :allDatas="allDatas" ref="component" />
    </div>
  </div>
</template>

<script>
import { api_request } from "@/util/network";
import bus from "@/util/eventBus";
import Breadcrumbs from "@/components/Breadcrumbs";
import TabList from "@/components/TabList";
import chilCom from "./component/chilCom";

export default{
	data(){
		return {
		  tabId: 0,
	      allDatas: {},
	      curCom: ""
		}
	},
	created() {
	  this.getCurIdData(this.$route.params.id);
	
	  bus.$on("refresh", () => {
	    this.getCurIdData(this.$route.params.id);
	  });
	},
	methods:{
		tabEvent(id) {
	      this.tabId = id;
	    },
		getCurIdData(id) {
		  this.$http
		    .get(`/api/${id}`)
		    .delegateTo(api_request)
		    .then(data => {
		      this.allDatas = data;
		      this.curCom = COMPONENTS[this.tabId];
		    });
		},
		
	},
	watch: {
	    tabId(v) {
	      this.curCom = COMPONENTS[v];
	    }
  	},
}
</script>

childCom.vue

methods: {
    save() {
      if (this.$refs.form.validate()) {
        let payload = {
          new_name: this.name,
          new_options: this.form
        };
        const promise = modify_request(this.$route.params.id, payload)
          .then(() => {
            this.$store.commit("show_sheet", { show: false });
            bus.$emit("refresh");
            return "更新成功";
          })
          .catch(({ code, message }) => {
            throw `修改失败:${this.$t(
              "api." + code
            )}, 额外信息: ${"api." + JSON.stringify(message)}`;
          });
        this.$snackbar.delegate(promise);
      }
    },
  },
### Vue.jsEventBus使用教程 #### 创建全局 Event Bus 为了简化组件间的通信,在 Vue 项目中可以创建一个全局的 `EventBus`。这可以通过实例化一个新的 Vue 对象并将其挂载到 Vue 原型链上来实现,从而使得所有的 Vue 组件都可以访问这个共享的事件总线[^1]。 ```javascript // main.js 或入口文件中定义全局EventBus var EventBus = new Vue(); Object.defineProperty(Vue.prototype, '$bus', { get: function () { return EventBus; } }); ``` 这样做的好处在于任何地方只需要通过 `this.$bus` 就能获取到该全局对象,而无需再单独导入其他模块。 #### 发送与接收自定义事件 当需要触发某个特定的操作时,可以在源组件里调用 `$emit()` 方法来广播一条消息给目标组件;而在目的端,则利用 `$on()` 来订阅感兴趣的事件名称及其处理逻辑[^2]。 - **发送事件** 在想要发出通知的地方执行如下代码: ```javascript this.$bus.emit('eventName', payload); // 'eventName' 是要发布的事件名字,payload 可选参数用于携带数据 ``` - **接收事件** 于希望响应此信号的位置设置侦听器: ```javascript this.$bus.on('eventName', callbackFunction); ``` 其中 `callbackFunction` 应是一个接受至少一个参数的方法,用来接收由发布者传递过来的数据。 #### 完整示例展示 下面给出一段完整的例子说明如何在一个简单的 Vue 应用程序内部运用上述机制完成跨组件的消息交换功能[^3]。 假设有一个父级容器包含了两个子部件 A 和 B ,现在想让 A 向 B 发送更新请求。 ##### 子组件A (Sender) ```html <template> <button @click="sendMessage">Send Message</button> </template> <script> export default { methods: { sendMessage() { this.$bus.emit('message-from-a', { message: 'Hello from Component A!' }); } } } </script> ``` ##### 子组件B (Receiver) ```html <template> <div>{{ receivedMessage }}</div> </template> <script> export default { data() { return { receivedMessage: '' }; }, created() { this.$bus.on('message-from-a', ({ message }) => { this.receivedMessage = message; }); } }; </script> ``` 以上即为基于 Vue.js 构建的应用程序间采用事件驱动模式来进行交互的一种常见做法——借助内置工具构建轻量级的消息中心(EventBus),它不仅易于理解和上手操作而且能够有效减少不必要的依赖关系复杂度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值