Detect Back Button in Navigation Guards of Vue-Router

前端 未结 3 1543
故里飘歌
故里飘歌 2020-12-06 19:53

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.

This is what I have:



        
3条回答
  •  -上瘾入骨i
    2020-12-06 20:31

    This is the only way that I've found:

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

提交回复
热议问题