call a function every time a route is updated vue.js

Costantin picture Costantin · Aug 10, 2017 · Viewed 9.3k times · Source

I have integrated intercom in my app and I need to call window.Intercom('update'); every-time my url changes.

I know I could add it on mounted() but I rather not modify all my component and do it directly using the navigation guards. (Mainly to avoid to have the same code in 10 different places.

At the moment I have:

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
})

This runs intercom('update') before changing the url, while I need to run it after the url changes.

Is there a hook which runs just when the url has changed? How can I do this?

Thanks

Answer

Phil picture Phil · Aug 10, 2017

Wasn't sure this would work as what you already have seems like it should be fine but here goes...

Try watching the $route object for changes

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