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

10,385

Solution 1

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

Solution 2

I just came up with another solution beyond Phil's, you could also use Global Mixin. It merges its methods or lifecycle hooks into every component.

Vue.mixin({
  mounted() {
    // do what you need
  }
})
Share:
10,385
Costantin
Author by

Costantin

Updated on June 08, 2022

Comments

  • Costantin
    Costantin almost 2 years

    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