This time I will bring you vue to determine whether the user is logged in. What are the precautions for vue to determine whether the user is logged in? The following is a practical case, let's take a look.
By judging whether the user has logged in, if not logged in, jump to login Routing, if logged in, jump normally.
1. First, give a status before and after user login to identify whether the user is logged in (vuex is recommended); Simply use vuex to express it. If you don’t know, you can go to the official website to see more;
import Vue from ‘vue‘ import Vuex from ‘vuex‘ Vue.use(Vuex); var state = { isLogin:0, //初始时候给一个 isLogin=0 表示用户未登录 }; const mutations = { changeLogin(state,data){ state.isLogin = data; } };
2. Change the login status when the user logs in; this.$store.commit(‘changeLogin‘,‘100‘)
//登录后改变登录状态 isLogin = 100 ;
Three, here comes the key point; Add the
Navigationhook to your route entry. See the code for the specific meaning;
1. Set the route that needs to be verified{ path: ‘/admin‘,
component: Admin,
meta:{auth:true} // 设置当前路由需要校验 不需要校验的路由就不用写了;不要问为什么,自己去看官网
}
router.beforeEach((to,from,next) => {
if(to.matched.some( m => m.meta.auth)){
// 对路由进行验证
if(store.state.isLogin==‘100‘) { // 已经登陆
next() // 正常跳转到你设置好的页面
}
else{
// 未登录则跳转到登陆界面,query:{ Rurl: to.fullPath}表示把当前路由信息传递过去方便登录后跳转回来;
next({path:‘/login‘,query:{ Rurl: to.fullPath} })
}
}else{
next()
}
})
The above is the detailed content of Vue determines whether the user is logged in. For more information, please follow other related articles on the PHP Chinese website!