vue使用bus进行兄弟组件传值

方法一:通过bus中转

//1.新建bus.js

import Vue from 'vue'
export default  new Vue
//2.在需要传值和接受值的vue文件中,各自引入bus.js

import bus from '../util/bus'
//3.定义传值的方法,使用bus.$emit('methodName',data), methodName是自定义的方法名


methods: {
    trans(){
      bus.$emit('test',this.helloData)
    }
  },
//4.在要接收值的组件里,使用bus.on('methodName',val =>{ }) ,val 就是传过来的值
 mounted(){
    bus.$on('test',val=>{
      console.log(val);
      this.cdata = val
    })
}

如果要传多个值:

 bus.$emit('test',data1,data2,data3……)
//同样接收时候,需要接收多个值

bus.$on(test,(val,val2,val3……)=>{
     console.log(val,val2,val3)
})

如果需要不触发事件,就把值传递给兄弟组件,那么必须通过异步的方法传递,例如axios或者setTimeout

 // 不通过点击事件,把数据传递给兄弟组件,一定要setTimeout,或者axios请求
setTimeout(() => {
    bus.$emit('test',data)
}, 2000);

@完整例子:

bus.js

import Vue from 'vue'
export default  new Vue

App.vue




子组件HelloWorld.vue

import Vue from 'vue'
export default  new Vue




子组件Child.vue



方法二:通过vue的原型上定义一个bus,其实和 方法一类似,实现起来有些区别

还有一种比较好的方式,也是我比较推荐的

App.vue或者main.js中定义
Vue.prototype.eventBus = new Vue();

组件A

this.eventBus.$emit('eventName', params)

组件B

this.eventBus.$on('eventName', params)

方法三:直接通过$root传值

组件A

this.$root.$emit('eventName', params)

组件B

this.$root.$on('eventName', params)

注意:事件名必须保持统一

写在最后:bus通信的原理分析
class Bus {
  constructor() {
    this.callbacks = {}
  }
  $on(name, fn) {
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(fn)
  }
  $emit(name, args) {
    if (this.callbacks[name]) {
      this.callbacks[name].forEach(cb => cb(args))
    }
  }
}
// main.js
Vue.prototype.$bus = new Bus()
// child1
this.$bus.$on('foo', handle)
// child2
this.$bus.$emit('foo')

你可能感兴趣的:(vue使用bus进行兄弟组件传值)