每次更新路由时调用一个函数 vue.js
call a function every time a route is updated vue.js
我在我的应用程序中集成了对讲机,每次 url 更改时我都需要调用 window.Intercom('update');
。
我知道我可以在 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
})
这个 运行s intercom('update')
在更改 url 之前,而我需要 运行 它在 url 更改之后。
是否有 url 发生变化时 运行 的钩子?
我该怎么做?
谢谢
不确定这是否会起作用,因为您已经拥有的东西看起来应该没问题,但这里...
尝试 watching the $route
object 进行更改
new Vue({
// ...
watch: {
'$route': function(to, from) {
Intercom('update')
}
}
})
除了 Phil 的解决方案之外,我还想出了另一个解决方案,您也可以使用 Global Mixin。它将其方法或生命周期挂钩合并到每个组件中。
Vue.mixin({
mounted() {
// do what you need
}
})
我在我的应用程序中集成了对讲机,每次 url 更改时我都需要调用 window.Intercom('update');
。
我知道我可以在 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
})
这个 运行s intercom('update')
在更改 url 之前,而我需要 运行 它在 url 更改之后。
是否有 url 发生变化时 运行 的钩子? 我该怎么做?
谢谢
不确定这是否会起作用,因为您已经拥有的东西看起来应该没问题,但这里...
尝试 watching the $route
object 进行更改
new Vue({
// ...
watch: {
'$route': function(to, from) {
Intercom('update')
}
}
})
除了 Phil 的解决方案之外,我还想出了另一个解决方案,您也可以使用 Global Mixin。它将其方法或生命周期挂钩合并到每个组件中。
Vue.mixin({
mounted() {
// do what you need
}
})