【问题标题】:Trying to capture events on vue.js 2, but without success尝试在 vue.js 2 上捕获事件,但没有成功
【发布时间】:2018-12-14 08:24:30
【问题描述】:

我在使用 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
    }
  })
}

【问题讨论】:

  • 您的代码读取方式看起来就像您将 bus 作为插件附加到 Vue 实例。你有吗?
  • 是的,我将总线作为插件连接。
  • 请同时提供该代码
  • 另外,不使用事件总线,使用vuex 可能更容易。
  • 是的,im using vuex to other things, but for this i think its 没有必要,因为它太简单了......而且应该可以工作。

标签: vue.js vuejs2 event-bus


【解决方案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)
                }
            }
         })
      })
  }`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    相关资源
    最近更新 更多