组件通信-广播通信

发布于 2019-08-29  约 6 分钟
序言:vue组件通信方式大家都会有所了解,大多涉及到的也都是父子组件通信或者是兄弟组件通信,至于祖孙组件通信大多使用Vuex仓库实现。本文将使用一种全新的方式实现组件(无论隔几代)间通信。

1、封装广播方法

//emitter.js
function broadcast(componentName, eventName, params) {
  this.$children.forEach(child => {
    const name = child.$options.name;
    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) {
      let parent = this.$parent || this.$root;
      let name = parent.$options.name;

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

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

2、组件通信案例

//Index.vue
<template>
  <div>
    <component-a>
      <component-b></component-b>
    </component-a>
  </div>
</template>

<script>
import ComponentA from './A';
import ComponentB from './B';

export default {
  name: 'list',
  components: {
    ComponentA,
    ComponentB   
  },
  data() {
    return {
    }
  },
}
</script>
//A.vue
<template>
  <div>
    <button @click="greetB">向组件B发送消息</button>
    <slot></slot>
  </div>
</template>

<script>
  import Emitter from '../../assets/js/emitter.js';

  export default {
    name: 'componentA',
    mixins: [ Emitter ],
    created() {
      //监听子组件B传过来的问候
      this.$on("sendToA", this.showMessage);
    },
    methods: {
      showMessage(text) {
        window.alert(text);
      },
      greetB() {
        //向子组件B问候
        this.broadcast('componentB', 'sendToB', 'Hello B!, i love you');
      }
    }
  }
</script>
//B.vue
<template>
  <div>
    <button @click="greetA">向组件A发送消息</button>
  </div>
</template>

<script>
import Emitter from '../../assets/js/emitter.js';

export default {
  name: 'componentB',
  mixins: [ Emitter ],
  created () {
    //监听父组件A传过来的问候
    this.$on('sendToB', this.showMessage);
  },
  methods: {
    showMessage(text) {
      window.alert(text);
    },
    greetA() {
      //向父组件A问候
      this.dispatch("componentA", "sendToA", "hello A!, i love you too");
    }
  }
}
</script>

运行结果:
图片描述

阅读 205发布于 2019-08-29

推荐阅读
目录