检测Vue-Router导航护罩中的后退按钮 [英] Detect Back Button in Navigation Guards of Vue-Router

查看:161
本文介绍了检测Vue-Router导航护罩中的后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改路线,对我来说很重要. 因此,我想抓住浏览器或gsm的后退按钮更改路线的时间.

How the route is changed, matters for my case. So, I want to catch when the route is changed by a back button of browser or gsm.

这就是我所拥有的:

router.beforeEach((to, from, next) => {
  if ( /* IsItABackButton && */ from.meta.someLogica) {
    next(false) 
    return ''
  }
  next()
})

是否可以使用一些内置解决方案代替IsItABackButton注释?我猜Vue-router本身还没有,但是任何解决方法都可以在这里工作.还是会有另一种更好的方式来识别它?

Is there some built-in solutions that I can use instead of IsItABackButton comment? Vue-router itself hasn't I guess but any workaround could also work here. Or would there be another way preferred to recognize it?

推荐答案

这是我发现的唯一方法:

This is the only way that I've found:

我们可以监听popstate,将其保存在变量中,然后检查该变量

We can listen for popstate, save it in a variable, and then check that variable

// This listener will execute before router.beforeEach only if registered
// before vue-router is registered with Vue.use(VueRouter)

window.popStateDetected = false
window.addEventListener('popstate', () => {
  window.popStateDetected = true
})


router.beforeEach((to, from, next) => {
  const IsItABackButton = window.popStateDetected
  window.popStateDetected = false
  if (IsItABackButton && from.meta.someLogica) {
    next(false) 
    return ''
  }
  next()
})

这篇关于检测Vue-Router导航护罩中的后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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