Vue非父子组件通讯之$on与$emit事件总线方法

因为Vue是单向数据流,父子组件传递数据可经过props属性向下传递属性。如两个非父子组件想要传递一个数据就无法经过props来传递了。Vue官方有本身的Vuex作全局状态管理,这对于大型项目来讲很是有用。经过共有数据放在store中,全部组件都可拿到共有数据,本节不作探讨。对于简单的兄弟组件间的数据传递,官方还提供了事件总线来传递数据。javascript

// 定义一个bus文件

import Vue from 'vue';

export default new Vue();

经过定义bus文件暴露出一个空的Vue实例做为中央事件总线,在须要接收数据的组件中监听($on),在传递数据的组件中触发事件($emit)。具体方法见代码html

数据发送方:vue

<template>
  <div style="margin-bottom: 20px">
    <p-button type="primary" @click="send">send msg to compB</p-button>
  </div>
</template>

<script>
/**
 *  发送数据方, 在此组件中触发须要发送数据的方法
 */

import button from '../../packages/Button.vue';
import Bus from './bus';

export default {
  name: 'comp-a',
  data() {
    return {
      msg: 'this is a msg from compA',
    }
  },
  components: {
    'p-button': button,
  },
  methods: {
    send() {
      Bus.$emit('sendMsg', this.msg)
    }
  }
}
</script>

数据接收方:java

<template>
  <div>
    msg from: {{ msg }}
  </div>
</template>

<script>
/**
 * 数据接收方,在此组件中监听发送方的方法
 */

import Bus from './bus';
export default {
  name: 'comp-b',
  data() {
    return {
      msg: ''
    }
  },
  created() {
    Bus.$on('sendMsg', (msg) => this.msg = msg)
  }
}
</script>

最终效果:this

固然还有更好的方法,欢迎评论赐教!code