在下面的代码中:
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/