vue 跨层级通信 (elment-ui的跨层级通信)

$emit和on

对于ChildA包裹ChildB的组件通信,可以采用elment-ui封装的通信,原理是通过递归去找到符合条件的$parent和$children,然后通信。
这种方法对于封装组件比较友好,也好管理通信,如果使用event-bus,多人合作可能比较难管理

emitter.js

function broadcast(componentName, eventName, params) {
  this.$children.forEach((child) => {
    var name = child.$options.componentName;

    if (name === componentName) {
      child.$emit.apply(child, [eventName].concat(params));
    } else {
      broadcast.apply(child, [componentName, eventName].concat([params]));
    }
  });
}
export default {
  methods: {
    dispatch(componentName, eventName, params) {
      var parent = this.$parent || this.$root;
      var name = parent.$options.componentName;

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent;

        if (parent) {
          name = parent.$options.componentName;
        }
      }
      if (parent) {
        parent.$emit.call(parent, eventName, params);
      }
    },
    broadcast(componentName, eventName, params) {
      broadcast.call(this, componentName, eventName, params);
    }
  }
};

父组件

<template>
  <div>
    <div>A组件</div>
    <h3>{{ mes }}</h3>
    <hr />
    <slot></slot>
  </div>
</template>
<script>
import emitter from "./emitter";
export default {
  name: "childA",
  componentName: "childA",
  mixins: [emitter],
  data() {
    return {
      mes: "",
    };
  },
  mounted() {
    this.$on("change", (msg) => {
      this.mes = msg;
    });
    this.broadcast("childB", "getmesg", "我是childA的内容");
  },
};
</script>

childB组件

<template>
  <div>
    b组件
    <h3>{{ mes }}</h3>
    <button @click="change">changeA</button>
  </div>
</template>
<script>
import emitter from "./emitter";
export default {
  name: "childB",
  componentName: "childB",
  mixins: [emitter],
  data() {
    return {
      mes: "",
    };
  },
  mounted() {
    this.$on("getmesg", (msg) => {
      this.mes = msg;
    });
  },
  methods: {
    change() {
      this.dispatch("childA", "change", "我是b组件的内容");
    },
  },
};
</script>

代码地址:代码地址

posted @   黑黑哈哈  阅读(423)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· SQL Server统计信息更新会被阻塞或引起会话阻塞吗?
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 传国玉玺易主,ai.com竟然跳转到国产AI
· 自己如何在本地电脑从零搭建DeepSeek!手把手教学,快来看看! (建议收藏)
· 我们是如何解决abp身上的几个痛点
· 如何基于DeepSeek开展AI项目
历史上的今天:
2017-03-29 webstrom 里面使用github
2017-03-29 webstrom 使用git
点击右上角即可分享
微信分享提示