简体   繁体   中英

How to know the routes that a user has visited in a SPA with Vue & Vue Router

I'd like to know all the routes a user has visited. Do Vue Router (v4) or some Browser API exposes this information?

Why I need this information?

I need to distinguish when a user enters the site for the first time or not. When a user which is logged in tries to enter the login page, I redirect him/her to home page only if the numbers of routes the user has visited is 0 (first time enter). On the other hand, if a user has visited some routes, I cancel the navigation (stays in the current page).

Here is the pseudocode of what I'm trying to achieve:

router.beforeEach((to) => {
    if (to.name === 'login' && userStore.uid.length) {
      if ( determineNumbersOfRoutesUserHasVisited() ) {
        return false
      }
      return { name: 'home' }
    }

    if (to.name !== 'login' && !userStore.uid.length) {
      return { name: 'ingresar' }
    }
  })

Above userStore.uid.length is an ID. If that ID has something, the user is logged in. Also, determineNumbersOfRoutesUserHasVisited() is not implemented yet, It's just pseudocode.

I think you can use the from argument of router.beforeEach() for that. Something like:

router.beforeEach((to, from) => {
   if (to.name === ‘login’ && !from.name) {
       /// first time, since from is empty
   } else if (to.name === ‘login’) {
       return false; /// Cancel navigation
   }
   next();
})

See docs here. I think that you should name all your routes, otherwise name will be empty also in other cases when testing from.name .

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM