vuejs / vue-router

🚦 The official router for Vue 2
http://v3.router.vuejs.org/
MIT License
18.99k stars 5.06k forks source link

History state key as timestamp to detect back/forward navigation #2571

Open jakob-e opened 5 years ago

jakob-e commented 5 years ago

What problem does this feature solve?

Using Date.now() as key will provide a unique and comparable* identifier in relation to history navigation allowing back/forward navigation to be detected and used to define transition directions (slide left/right) etc.... and maybe it could be the first step in having vue-router provide this information out of the box :-)

*the current performance.now key does not ensure increment upon re-enter. image

A quick detection example based on Date.now as key:

//  direction   
//  -1 = history.back
//   0 = normal route
//   1 = history.forward 
let direction = 0;

//   key value of the from route (0 = entering)
let fromKey = 0;

router.beforeEach((to, from, next) => {
    //  add state in case it's missing 
    if(!history.state) { history.replaceState({key: Date.now() }, to.name, location.href); }

    //  get state key from history 
    const toKey = history.state.key;

    //  if we are entering  or the from and to keys (time-stamps) are identical => normal route
    //  if from is less than to – to was created after from    => history.forward
    //  if from is less than to – to was created before from   => history.back 
    direction = !fromKey || fromKey === toKey ? 0 : fromKey < toKey ? 1 : -1;   

    //  call next
    next();
})

router.afterEach((to, from) => {
    //  use nextTick to await key to be generated 
    Vue.nextTick(vm => { 

        //  save key for next beforeEach 
        fromKey = history.state.key; 
    })
})

What does the proposed API look like?

function genKey () {
  return Date.now()  // current fallback
}
hminghe commented 5 years ago

I also need to

matej-svejda commented 5 years ago

What is the status for this issue? Is there a reason why this hasn't been included in the latest release?