我在一个名为EvenBus
的文件中创建了一个名为app.js
的全局vuejs事件,如下所示:
window.EventBus = new Vue();
从数据库中删除某个人后,我会重定向到home
页面并发出一个名为deleted
的事件,如下所示:
import {app} from '../app';
export default {
methods: {
deleteMe: function () {
axios.delete('/api/persons/' + this.person.id)
.then(response => {
window.location.href = '/home';
EventBus.$emit('deleted', {
notification_msg: 'This person has been successfully deleted.',
});
})
},
}
在页面主页上,我插入了一个标记<notify></notify>
,该标记链接到名为notify.vue
的组件。
在这个组件中,我添加了以下脚本:
import {app} from '../app';
export default {
/* ... */
mounted() {
let that = this;
console.log(EventBus);
EventBus.$on('deleted', function(data){
alert('person deleted!!' + data.notification_msg);
that.msg_text = data.notification_msg;
});
},
}
当删除发生时,我成功地重定向到home
页面,但没有任何反应。 alert('person deleted!!...')
永远不会出现。
代码执行时没有错误。
我是否遗漏了一些东西让我的组件听取发出的事件?
修改
console.log(EvenBus);
文件中写的notify.vue
行显示有一个名为“已删除”的事件。 (参见下面的版画屏幕)
答案 0 :(得分:1)
这里的问题是当执行这行代码时,
window.location.href = '/home';
您所在的页面将替换为/home
页面。因此,它可能永远不会到达发出事件的行,如果它发生了,那么在加载页面时,侦听事件的对象就会消失。
您可能希望了解如何使用VueRouter以便不破坏页面。除此之外,可能告诉服务器何时重定向,它需要在页面加载时显示通知。