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是自定义的方法名

<button @click="trans()">传值</button>
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

<template>
    <div id="app">
        <HelloWorld />
        <child></child>
    </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";
import Child from "./components/Child";
export default {
    name: "App",
    components: {
        HelloWorld,
        Child,
    },
};
</script>

子组件HelloWorld.vue

import Vue from 'vue'
export default  new Vue


<template>
    <div>
        <button @click="trans()">传值</button>
    </div>
</template>
<script>
import bus from "../util/bus";
export default {
    name: "HelloWorld",
    data() {
        return {
            helloData: "hello",
        };
    },
    methods: {
        trans() {
            bus.$emit("test", this.helloData);
        },
    },
};
</script>

子组件Child.vue

<template>
    <div>{{cdata}}</div>
</template>
<script>
import bus from "../util/bus";
export default {
    name: "Child",
    data() {
        return {
            cdata: "子数据",
        };
    },
    mounted() {
        bus.$on("test", (val) => {
            console.log(val);
            this.cdata = val;
        });
    },
};
</script>

方法二:通过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')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。