【问题标题】:Vue 2.0 instance is not hearing events emitted by vue-router componentsVue 2.0 实例没有听到 vue-router 组件发出的事件
【发布时间】:2017-01-22 00:34:27
【问题描述】:
我正在使用 Vue 2.0-rc.6(目前最新)和 Vue-router 2.0-rc.5(目前最新)。
我尝试在我的一个路由器组件中执行 this.$emit('custom-event'),并在我的 Vue 实例中执行 this.$on('custom-event', () => { console.log('I heard an event') }),但未监听该事件。路由器组件本身听到了事件,但没有听到 Vue 实例。
有什么想法吗?
看看这个jsfiddle。
【问题讨论】:
标签:
javascript
vue.js
vuejs2
vue-router
【解决方案2】:
来自 $emit 的事件不会传播到父实例。
父级必须在模板中的组件上主动监听。
<router-view @eventname="callbackMethod" />
【解决方案3】:
使用观察者我们可以实现同样的事情,意味着当我的路线更新时,我们可以通过观察者捕捉事件。
watch: {
'$route': function(to, from) {
console.log('To :', to.path); // current route
console.log('from:', from.path); // old route
}
}