简体   繁体   English

Vue 2.0 实例听不到 vue-router 组件发出的事件

[英]Vue 2.0 instance is not hearing events emitted by vue-router components

I am using Vue 2.0-rc.6 (latest at the moment) and Vue-router 2.0-rc.5 (latest at the moment).我正在使用 Vue 2.0-rc.6(目前最新)和 Vue-router 2.0-rc.5(目前最新)。

I tried to do this.$emit('custom-event') in one of my router components, and this.$on('custom-event', () => { console.log('I heard an event') }) in my Vue instance but the event was not being listened.我试图在我的路由器组件之一中执行this.$emit('custom-event') ,而this.$on('custom-event', () => { console.log('I heard an event') })在我的 Vue 实例中,但没有监听事件。 The router component itself was hearing the event but not the Vue instance.路由器组件本身正在侦听事件,但没有侦听 Vue 实例。

Any idea?任何的想法?

Check out this jsfiddle .看看这个jsfiddle

An event from $emit is not propagated to the parent instance.来自 $emit 的事件不会传播到父实例。 The parent has to listen for it on the component in the template actively.父级必须主动在模板中的组件上监听它。

<router-view @eventname="callbackMethod" />

Thanks to LinusBorg in http://forum.vuejs.org/topic/5235/vue-2-0-instance-is-not-hearing-events-emitted-by-vue-router-components/2 for pointing out that an event from $emit is not propagated to the parent instance.感谢http://forum.vuejs.org/topic/5235/vue-2-0-instance-is-not-hearing-events-emitted-by-vue-router-components/2 中的LinusBorg 指出来自 $emit 的事件不会传播到父实例。

I didn't make it work though by using the suggested solution by LinusBorg.虽然我没有使用 LinusBorg 建议的解决方案让它工作。 Instead, I made it working by doing this.$router.app.$emit('eventname')相反,我通过这样做来让它工作this.$router.app.$emit('eventname')

using watcher we can achieve the same thing, Mean when my routes are updated then we can catch an event through watcher.使用观察者我们可以实现同样的事情,意味着当我的路线更新时,我们可以通过观察者捕捉事件。

    watch: {
        '$route': function(to, from) {
              console.log('To :', to.path); // current route
              console.log('from:', from.path); // old route
         }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM