簡體   English   中英

Vue 2.0 實例聽不到 vue-router 組件發出的事件

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

我正在使用 Vue 2.0-rc.6(目前最新)和 Vue-router 2.0-rc.5(目前最新)。

我試圖在我的路由器組件之一中執行this.$emit('custom-event') ,而this.$on('custom-event', () => { console.log('I heard an event') })在我的 Vue 實例中,但沒有監聽事件。 路由器組件本身正在偵聽事件,但沒有偵聽 Vue 實例。

任何的想法?

看看這個jsfiddle

來自 $emit 的事件不會傳播到父實例。 父級必須主動在模板中的組件上監聽它。

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

感謝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')

使用觀察者我們可以實現同樣的事情,意味着當我的路線更新時,我們可以通過觀察者捕捉事件。

    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