User login? Vue? Life cycle?

wrote a registration login page in vue. Now the login successfully caches the data locally with localStorage, but I want to achieve a function, that is, if you enter APP, you can go directly to the home page of APP if you have already logged in. If you do not log in to APP, you will be able to go back and forth to click on the bottom navigation switch page when you enter the personal Center. Pray for the Great God to refer to the teaching reform

Mar.04,2021

this requires a navigation guard to determine, portal https://router.vuejs.org/zh-c.


router.beforeEach ((to, from, next) = > {
var userInfo= JSON.parse (sessionStorage.getItem ('userInfoStorage')); / / get the user information cached by the browser
if (userInfo) {/ / if any, go directly to the front page

next();

} else {

if(to.path=='/login'){//next()
  next();
}else{//;
  next('/login');
}

}
})


1. You can jump to the login page under the root component created to determine whether the user stored in localStorage does not exist, and the existing logic handles it on its own.
2, or use beforeEach to check the document for yourself.


to split the requirements of the subject

1. Enter APP if you are already logged in, go directly to the APP home page
here you need to do 2 steps: a. Set the app entry link to your app home link; 2. Check whether there is data in the global front guard (note here that the backend does not set a timeout, otherwise do not do so). If so, go to the home page, and if not, go to the login page

.
router.beforeEach((to, from, next) => {
  // 
  if (localStorage.getItem('user_data') || to.fullPath === '/login') {
    next()
  } else {
    // 
    next({ path: '/login' })
  }
})

2. If you are not logged in to APP, the login page
answers as shown above

3. After logging in, go to the personal center
this can be judged in your login interface. If the login is successful, jump to the personal center

here again, if the backend has imposed a login validity limit, it will be judged above that there will be cases where the user has already timed out but the cache is there.
at this point, the user clearly logs in, but does not get the interface data.
the solution is that you can determine whether the status code returned by the API is whether the user is not logged in or timed out (what is the status code that communicates with the backend when the user is not logged in or the login timeout) in the interface you encapsulate (assuming you encapsulate it). If so, jump to the login page

.
Menu