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>

代码地址:代码地址

原文地址:https://www.cnblogs.com/heihei-haha/p/14593821.html