vue组件传值之事件总线

如果想要使用事件总线进行组件之间的传值,首先我们需要将$eventBus挂载到vue实例上面

然后在A页面使用this.$eventBus.$emit("命名", 值);触发事件总线

B页面实现监控this.$eventBus.$on("命名", (event) => {}(需要注意,此处命名需要和this.$eventBus.$emit之中的命名保持一致)

需要注意一点就是,事件总线用完需要移除,一般会在组件销毁生命周期内移除,避免多次触发

下面是代码:

 

//main.js
import Vue from 'vue'
Vue.prototype.$eventBus = new Vue()//挂载到vue实例上全局定义

//bortherOne.vue
<template>
  <div>
    <button @click="btn">点击传值</button>
    bortherOne
  </div>
</template>
<script>
export default {
  name: "bortherOne",
  data() {
    return {
      bortherOneValue: "我是bortherOne",
    };
  },
  mounted() {},
  methods: {
    btn() {
      this.$eventBus.$emit("deliverValue", this.bortherOneValue);//发起
    },
  },
};
</script>

//bortherTwo.vue
<template>
  <div>
    <p>bortherTwo{{ bortherTwoValue }}</p>
  </div>
</template>

<script>
export default {
  name: "bortherTwo",
  data() {
    return {
      bortherTwoValue: "我是bortherTwo,我负责接收值",
    };
  },

  mounted() {
    this.$eventBus.$on("deliverValue", (event) => {//监听接收传过来的值
      this.bortherTwoValue = event;
      console.log(this.bortherTwoValue);
      console.log(event, "event");
      this.getData(event);
    });
  },
  methods: {
    getData(event) {
      console.log(event, "在getdata里面打印接收到的值");
    },
  },
  beforeDestory() {
    this.$eventBus.$off("deliverValue");//避免多次触发
  },
};
</script>

 除了上面这种初始时候在main.js之中直接将eventBus挂载到vue实例上面的方法,我们还可以是使用封装js文件的方法实现事件总线传值,代码如下:

//bus.js
import Vue from 'vue';

// 使用 Event Bus
const bus = new Vue();

export default bus;




//使用的时候
import bus from '../utils/bus.js
bus.$emit("collapse", this.collapse);//触发
bus.$on("collapse", data => {})//监听
bus.$off("collapse")//移除

封装js文件的方法,多了一步导入需要用到的文件,其他触发,移除,监听基本一致这里不过多赘述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值