Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Vuejs$emit不';Don’别在电话里开枪_Javascript_Node.js_Vue.js - Fatal编程技术网

Javascript Vuejs$emit不';Don’别在电话里开枪

Javascript Vuejs$emit不';Don’别在电话里开枪,javascript,node.js,vue.js,Javascript,Node.js,Vue.js,在以下代码中: export default { props: ['note'], methods: { remove(){ NoteRepo.remove(this.note, (err) => { if (err) { console.log('Should Fire') this.$emit('alerted', {

在以下代码中:

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函数时,控制台会记录“应该触发”,但不会触发$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')
                }
            })
        }
    }
}
它起作用了。我已经尝试分配
\u this=this
并使用它来激发$emit,但没有区别


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

因此,原来是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);
    }

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

您是否尝试过不使用箭头功能?我刚开始使用vue,但我似乎记得在文档中读到,在某些地方使用箭头函数时,无法正确绑定上下文。是的,如果我理解正确,在使用箭头函数时,
表示vue实例,因此在这种情况下,使用箭头函数是可以的。也就是说,我已经尝试过了(并且在这个过程中分配了
\u self=this
),没有什么不同。我尝试了各种方法给它取别名,但没有成功。我在这里找到了相关的一点:看起来arrow函数没有绑定到vm实例。@TheLoverter4865所建议的是正确的。要解决您的问题,请直接发出该事件,并让该事件处理程序处理NoteRepo.remove()。但我需要在回调上发出该事件。当回调失败并响应错误时,我需要告诉警报组件显示失败错误。还是我不明白?如果是这样,你能给我一个代码示例吗?