javascript - Vuejs $emit 不会在回调时触发

标签 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 函数时,控制台会记录“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 事件没有在回调中触发?

最佳答案

所以事实证明是 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);
    }

我不确定到底出了什么问题,但现在看来已经解决了。

关于javascript - Vuejs $emit 不会在回调时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40451053/

相关文章:

javascript - 从符号/它的字形中删除/忽略空白或墨迹

javascript - AngularJS 组件 : using binding object in controller

javascript - qq.FileUploader 在 AJAX 弹出窗口中加载时不起作用

javascript - 尝试使用 javascript/jQuery 在滚动上添加导航突出显示 - 计算元素高度时出错

mysql - 连接/查询 mysql node.js 和 postgreSQL 时出错

npm - 找不到相对于目录的预设 "stage-2"

node.js - 在 Apache 后面运行 express 应用程序时如何强制使用 SSL?

javascript - 类型错误 : Cannot read property 'config' of null at Class. 运行〜/node_modules/angular-cli/tasks/serve.js:22:61

javascript - nuxt layout - 为移动端和桌面端提供不同的布局

Laravel 6.0 app.js 只有 require ('.bootstrap' );?