【问题标题】:Vuejs $emit doesn't fire on callbackVuejs $emit 不会在回调时触发
【发布时间】:2017-03-19 23:06:18
【问题描述】:

在以下代码中:

export default {
    props: ['note'],
    methods: {
        remove(){
            NoteRepo.remove(this.note, (err) => {
                if (err) {
                    console.log('Should Fire')
                    this.$emit('alerted', {
                        type: 'error', 
                        message: 'Failed to remove note'
                    });
                }
            })
        }
    }
}

当 remove 函数被调用时,控制台会记录“Should Fire”,但 $emit 事件不会被触发。如果我像这样将 $emit 移到回调之外:

export default {
    props: ['note'],
    methods: {
        remove(){
            this.$emit('alerted', {
                type: 'error', 
                message: 'Failed to remove note'
            });

            NoteRepo.remove(this.note, (err) => {
                if (err) {
                    console.log('Should Fire')
                }
            })
        }
    }
}

它有效。我尝试分配 _this = this 并使用它来触发 $emit 但没有区别。

为什么 $emit 事件没有在回调中触发?

【问题讨论】:

  • 你试过不使用箭头函数吗?我刚开始使用 vue,但我似乎记得在文档中看到箭头函数在某些地方使用时无法正确绑定上下文。
  • 是的,如果我理解正确的话,使用箭头函数时this 代表Vue 实例,所以在这种情况下箭头函数就可以了。话虽如此,我已经尝试过(并在此过程中分配了_self = this)并且没有区别。我已经尝试了各种方法来给它起别名,但没有运气。
  • 我在这里找到了相关位:vuejs.org/v2/guide/instance.html#Properties-and-Methods 看起来箭头函数没有绑定到 vm 实例。
  • @theWanderer4865 的建议是正确的。要解决您的问题,请直接发出事件并让该事件处理程序处理 NoteRepo.remove()。
  • 但是我需要在回调中发出事件。当回调失败并以错误响应时,我需要告诉警报组件显示失败错误。还是我没有关注?如果是这样,您能否给我一个代码示例?

标签: javascript node.js vue.js


【解决方案1】:

所以事实证明是 NoteRepo 中的某些东西导致了问题。特别是 firebase 事件回调。

constructor () {
        super();

        // Initialize Firebase
        Firebase.initializeApp({
            apiKey: "xxx",
            authDomain: "xxx",
            databaseURL: "xxx",
            storageBucket: "xxx",
            messagingSenderId: "xxx"
        });

        this.ref = Firebase.database().ref('notes');
        this.attachFirebaseListeners();
    }

    attachFirebaseListeners() {
        this.ref.on('child_added', this.onAdded, this);
        this.ref.on('child_removed', this.onRemoved); // Removing 'this' here seems to of fixed it.
        this.ref.on('child_changed', this.onChanged, this);
    }

我不确定到底出了什么问题,但这似乎暂时解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2014-01-26
    • 2010-10-09
    • 1970-01-01
    相关资源
    最近更新 更多