2017-08-10 134 views
3

我在我的應用中集成了對講機,每次我的網址更改時都需要撥打window.Intercom('update');每次更新路由時都會調用一個函數vue.js

我知道我可以將它添加到mounted(),但我寧願不修改我的所有組件,直接使用navigation guards。 (主要是爲了避免有相同的代碼在10米不同的地方

目前,我有:

router.afterEach((to, from) => { 
    eventHub.$off(); // I use this for an other things, here is not important 
    console.log(window.location.href) // this prints the previous url 
    window.Intercom('update'); // which means that this also uses the previous url 
}) 

此更改URL之前運行intercom('update'),而我需要的URL更改後,運行它。

有它運行只是當URL已更改? 我怎樣才能做到這一點的鉤子?

感謝

+1

你可以試試[看着'$ route'對象(https://router.vuejs.org/en/essentials/dynamic-matching.html#reacting-to-params-changes)在' Vue'實例。 – Phil

+0

@thanksd我說它還沒有改變,因爲在第3行'console.log(window.location.href)'打印了以前的URL。例如從家裏我點擊/關於,它打印回家,然後我點擊/團隊它打印/關於等 – Costantin

+0

@Phil你的意思是在我的基本組件中添加一個觀察器?這可以工作..我只是通常嘗試避免觀察者,但在這裏它可能是有道理的 – Costantin

回答

6

不知道這會工作作爲你已經擁有的似乎應該是好的,但在這裏不用...

嘗試watching the $route object更改

new Vue({ 
    // ... 
    watch: { 
    '$route': function(from, to) { 
     Intercom('update') 
    } 
    } 
}) 
0

我只是想出了超越菲爾的另一個解決方案,你也可以使用Global Mixin。它將其方法或生命週期鉤子合併到每個組件中。

Vue.mixin({ 
    mounted() { 
    // do what you need 
    } 
}) 
相關問題