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

▼魔方 西西 提交于 2019-12-10 09:26:16

问题


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


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



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


来源:https://stackoverflow.com/questions/45602622/call-a-function-every-time-a-route-is-updated-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!