eventBus踩坑

前言:在vue中组件传值有很多方法,在不是特别大的项目中不需要非得使用Vuex,父子之间可用用props传值,非父子组件可以使用eventBus,使用过程中遇到一个小坑,记录一下。

eventBus就是导出了一个Vvue的实例

eventBus.js

import Vue from 'vue'
export default new Vue()

在search.vue页面中传递参数

eventBus.$emit('searchValue', this.searchValueObj);

在table.vue页面中接收参数

created() {
    eventBus.$on('searchValue', this.getParams)
  },
methods: {
    getParams (value) {
      this.searchValueObj = merge({}, value)
      console.log(this.searchValueObj)
      this.getList()
    },
}

但是。。。我在切换页面再切回来的时候第二次执行了两次,接口也掉了两次。

然后我在vue的issue中发现了尤大神提出的解决方案

img

就是说,这个$on事件是不会自动清楚销毁的,需要我们手动来销毁

beforeDestroy() {
  eventBus.$off('searchValue', this.getParams)
},

在这记录一下,希望遇到和我一样坑的人少走些弯路。附上issue的地址  https://github.com/vuejs/vue/issues/3399

猜你喜欢

转载自www.cnblogs.com/PrayLs/p/12811697.html
今日推荐