Vuejs $ emit不会在回调时触发

时间:2016-11-06 15:28:29

标签: 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', {
                        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')
                }
            })
        }
    }
}

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

为什么$ emit事件不会在回调中触发?

1 个答案:

答案 0 :(得分: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);
    }

我不确定到底出了什么问题,但这似乎暂时对它进行了排序。

相关问题