Skip to content

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

Open
@jakob-e

Description

@jakob-e

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions