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

Detect Back Button in Navigation Guards of Vue-Router

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

这是我的:

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

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

这是我找到的唯一方法:

我们可以侦听 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()
})

如@Yuci 所述,所有路由器钩子回调都在 popstate 更新之前执行(因此对这个用例没有帮助)

你能做什么:

methods: {
    navigate(location) {
        this.internalNavigation = true;
        this.$router.push(location, function () {
            this.internalNavigation = false;
        }.bind(this));
    }
}
  1. 用你自己的 'navigate' 函数包装 'router.push'
  2. 在调用 router.push 之前,将 'internalNavigation' 标志设置为 true
  3. 使用 vue router 'oncomplete' 回调将 internalNavigation 标志设置回 false

现在您可以在 beforeEach 回调中检查标志并相应地处理它。

router.beforeEach((to, from, next) => {
  if ( this.internalNavigation ) {
      //Do your stufff
  }
  next()
})

这很容易做到。

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      // History back position, if user click Back button
      return savedPosition
    } else {
      // Scroll to top of page if the user didn't press the back button
      return { x: 0, y: 0 }
    }
  }
})

检查这里: https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling

@yair-levy 的回答略有改进。

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

以下代码是我的 Nuxt 插件,用于防止由 back/forward 按钮触发的导航(用于 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
  })
}

在我的 Vue 应用程序中检测后退按钮导航而不是其他类型的导航时,我遇到了同样的问题。

我最后做的是在我真正的内部 App 导航中添加一个散列,以区分预期的 App 导航和后退按钮导航。

例如,在这条路线上 /page1 我想捕捉后退按钮导航以关闭打开的模型。假设我真的想导航到另一条路线,我将向该路线添加一个散列:/page2#force

beforeRouteLeave(to, from, next) {
    // if no hash then handle back button
    if (!to.hash) {
      handleBackButton();
      next(false); // this stops the navigation
      return;
    }
    next(); // otherwise navigate
}

这很简单,但很管用。如果您在应用中将它们用于更多用途,则需要检查哈希实际包含的内容。

performance.navigation 已弃用,所以请注意! https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation

当你想注册任何全局事件侦听器时,你应该非常小心。从注册时刻起每次都会调用它,直到您手动取消注册为止。对我来说,情况是我在创建组件时注册了 popstate 侦听器以侦听并在以下情况下调用某些操作:

  • 浏览器后退按钮
  • alt + 向后箭头
  • 鼠标中的后退按钮

被点击了。之后,我注销了 popstate 侦听器,以免在我不想调用它的其他组件中调用它,保持您的代码和方法调用干净:)。

我的代码示例:

    created() {
      window.addEventListener('popstate', this.popstateEventAction );
    },
    methods: {
      popstateEventAction() {
        // ... some action triggered when the back button is clicked
        this.removePopstateEventAction();
      },
      removePopstateEventAction() {
        window.removeEventListener('popstate', this.popstateEventAction);
      }
   }

此致!