在 Vue-Router 的 Navigation Guards 中检测后退按钮

新手上路,请多包涵

路线如何改变,对我来说很重要。所以,我想在路由被浏览器或 gsm 的后退按钮更改时捕捉到。

这就是我所拥有的:

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

有没有我可以使用的内置解决方案来代替 IsItABackButton 评论?我猜 Vue-router 本身没有,但任何解决方法也可以在这里工作。还是会有另一种首选方式来识别它?

原文由 Asqan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 427
2 个回答

这是我找到的唯一方法:

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

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

原文由 Nuno Balbona Pérez 发布,翻译遵循 CC BY-SA 4.0 许可协议

@yair-levy 回答略有改进。

push 包装到自己的 navigate 方法并不方便,因为您通常想从不同的地方调用 push ()。相反,路由器原始方法可以在一个地方进行修补,而无需更改剩余代码。

以下代码是我的 Nuxt 插件,用于防止由后退/前进按钮触发导航(在 Electron 应用程序中使用,以避免鼠标附加“后退”按钮导致后退,这会在 Electron 应用程序中造成混乱)相同的原理可用于 vanilla Vue 和跟踪通用后退按钮以及您的自定义处理。

 export default ({ app }, inject) => {
  // this is Nuxt stuff, in vanilla Vue use just your router intances
  const { router } = app

  let programmatic = false
  ;(['push', 'replace', 'go', 'back', 'forward']).forEach(methodName => {
    const method = router[methodName]
    router[methodName] = (...args) => {
      programmatic = true
      method.apply(router, args)
    }
  })

  router.beforeEach((to, from, next) => {
    // name is null for initial load or page reload
    if (from.name === null || programmatic) {
      // triggered bu router.push/go/... call
      // route as usual
      next()
    } else {
      // triggered by user back/forward
      // do not route
      next(false)
    }
    programmatic = false // clear flag
  })
}

原文由 farincz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题