Vuejs的$emit在回调中不触发

3
在下面的代码中:
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,但我似乎记得在文档中读到过,在某些地方使用箭头函数时,上下文绑定不正确。 - theWanderer4865
是的,如果我理解正确的话,当使用箭头函数时,this代表Vue实例,所以在这种情况下使用箭头函数是可以的。话虽如此,我已经尝试过(并在此过程中分配了_self = this),但没有任何区别。我尝试了各种方式来给它取别名,但都没有成功。 - evu
1
我在这里找到了相关的部分:http://vuejs.org/v2/guide/instance.html#Properties-and-Methods 看起来箭头函数没有绑定到vm实例。 - theWanderer4865
@theWanderer4865所建议的是正确的。为了解决您的问题,请直接发出事件,让该事件处理程序处理NoteRepo.remove()。 - Saurabh
但是我需要在回调函数中触发事件。当回调函数失败并响应错误时,我需要告诉警报组件显示失败错误。或者我没有理解对吗?如果是这样,你能否给我一个代码示例? - evu
我还应该提到,在回调函数中(箭头函数或在普通函数中重新分配给_self时),this指的是Vue实例。 - evu
1个回答

0

所以事实证明,问题出在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);
    }

我不确定出了什么问题,但现在似乎已经解决了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接