New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jakob-e opened this Issue Jan 7, 2019 · 0 comments

Comments

Projects
None yet
2 participants
@jakob-e
Copy link

jakob-e commented Jan 7, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment