Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Back Button in Navigation Guards of Vue-Router

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:

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

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?

like image 589
Asqan Avatar asked Aug 23 '18 07:08

Asqan


Video Answer


1 Answers

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()
})
like image 50
Nuno Balbona Pérez Avatar answered Sep 21 '22 09:09

Nuno Balbona Pérez