每次更新路由时调用一个函数 vue.js [英] call a function every time a route is updated vue.js

查看:24
本文介绍了每次更新路由时调用一个函数 vue.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我知道我可以将它添加到 mounted() 但我宁愿不修改我的所有组件而是直接使用 导航守卫.(主要是为了避免在10个不同的地方有相同的代码.

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.

目前我有:

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

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

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

是否有仅在 url 更改时运行的钩子?我该怎么做?

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

谢谢

推荐答案

不确定这是否会起作用,因为您已经拥有的看起来应该没问题,但是这里...

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

尝试观看$route 对象 用于更改

Try watching the $route object for changes

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

这篇关于每次更新路由时调用一个函数 vue.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆