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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果咱们的应用程序不需要类似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);
      }
    },
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值