每次路由更新时调用一个函数vue.js

Cos*_*tin 4 javascript intercom vue-router vue-component vuejs2

我在我的应用程序中集成了对讲机,我需要window.Intercom('update');每次更改我的网址.

我知道我可以添加它mounted()但我宁愿不修改我的所有组件并使用导航警卫直接进行.(主要是为了避免在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
})
Run Code Online (Sandbox Code Playgroud)

intercom('update')在更改url之前运行,而我需要在url更改后运行它.

是否有一个挂钩,当网址发生变化时才会运行?我怎样才能做到这一点?

谢谢

Phi*_*hil 14

不确定这会有效,因为你已经拥有它似乎应该没问题但是这里...

尝试观察$route对象的变化

new Vue({
  // ...
  watch: {
    '$route': function(to, from) {
      Intercom('update')
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

  • 参数的顺序应该是“从”到“从”,否则正是我想要的。 (2认同)