Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 225
Costantin Avatar asked Aug 10 '17 00:08

Costantin


2 Answers

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')
    }
  }
})
like image 87
Phil Avatar answered Sep 27 '22 19:09

Phil


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
  }
})
like image 22
choasia Avatar answered Sep 27 '22 20:09

choasia