【问题标题】: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


【解决方案1】:

感谢 http://forum.vuejs.org/topic/5235/vue-2-0-instance-is-not-hearing-events-emitted-by-vue-router-components/2 中的 LinusBorg 指出来自 $emit 的事件不会传播到父实例。

虽然使用 LinusBorg 建议的解决方案,但我并没有让它工作。相反,我通过 this.$router.app.$emit('eventname')

让它工作了

【讨论】:

    【解决方案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
               }
          }
      

      【讨论】:

        猜你喜欢
        • 2020-03-18
        • 2020-03-07
        • 1970-01-01
        • 2017-10-05
        • 2017-03-14
        • 2021-06-05
        • 2018-06-23
        • 2020-03-16
        • 2017-02-25
        相关资源
        最近更新 更多