尝试捕获vue.js 2上的事件,但未成功

时间:2018-07-05 19:08:39

标签: vue.js vuejs2 event-bus

我在使用vue.js 2捕获事件时遇到问题。我正在使用事件总线来发出和捕获事件。

在这段代码中,我编写了将引发事件的函数:

getLevelItems(parent) {
    this.$bus.$emit('get-level-items',{level: 'third', parent: parent})
},

在另一个方框中,我捕获了事件:

mounted() {
      this.$bus.$on('get-level-items', (obj) => {
        if (obj.level === 'third' && obj.parent === this.parent) {
          if (this.itemsNotFilled){
            this.getAllCategories(this.parent)
          }
        }
      })
    },

好,通过单击按钮发出事件,效果很好,但是,如果我想在另一个时刻发出事件,例如,在请求响应后,事件将被发出但不会被捕获。

prepareData(data) {
        _.forEach(data, (value) => {
          value.selected = this.categories.includes(value._id) ? true : false
          value.show = this.categories.includes(value._id) ? true : false
          if (value.show){
            this.getLevelItems(value._id)
          }    
        })
        return data
      },

eventbus.js

import Vue from 'vue'

const bus = new Vue()

export { bus }

export default function install (Vue) {
  Object.defineProperty(Vue.prototype, '$bus', {
    get () {
      return bus
    }
  })
}

1 个答案:

答案 0 :(得分:-1)

尝试使用nextTick:

`mounted() { 
    this.$nextTick(function () {
        this.$bus.$on('get-level-items', (obj) => {
            if (obj.level === 'third' && obj.parent === this.parent) {
                if (this.itemsNotFilled) {
                    this.getAllCategories(this.parent)
                }
            }
         })
      })
  }`