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);
      }
    },
  },

猜你喜欢

转载自blog.csdn.net/Kiruthika/article/details/120053175