vue Bus

 Bus作为一个中转站,实现非父子之间组件之间的通信.

  bus本质上是vue对象,传递的方法本质上就是emit与on

使用方法说明:

第一种:使用单独的js文件

  1 ,bus.js

   import Vue from 'vue'
   export default new Vue()
2 文件A
  import Bus from './bus.js'
 Bus.$emit('Assembly', this.elementValue)
3 文件B
  import Bus from './bus.js'
   // 用$on事件来接收参数   并且调用了在a组件中出发的方法
      Bus.$on('Assembly', (data) => {       
vm.name = data })

第二种:

1
全局定义
main.js
const Bus = new Vue();  //很重要----------------------

new Vue({
  el: '#app',
  router,
  // store,
  components: {
    App
  },
  data() {
    return {
      Bus      //很重要----------------------
    }
  },
  template: '<App/>'
})

2、a.vue 通过$emit发送一个ElEdrag事件,传的参数是hello

 this.$root.Bus.$emit("ElEdrag", 'hello');

3、b.vue 通过$on接受ElEdrag事件

this.$root.Bus.$on("ElEdrag", e => {}) e就是传过来的参数


第三种

1.在main.js中注册全局的bus 

Vue.prototype.bus=new Vue();

2.在组件中使用 

 子组建使用:this.bus.$emit('自定义事件名',实参)

原文地址:https://www.cnblogs.com/fanjiawen/p/14461968.html