老师,实际开发中做导航守卫判断用户是否登录,一般用什么判断
来源:4-4 Vue-router之导航守卫
小章鱼丸
2019-12-15

像这里if(用户没登录),就让他去跳转登录页,那这个if后面括号里的条件(判断用户是否登录)一般是用什么判断的呢?
1回答
-
夏筱晗
2019-12-16
登录时在cookie中存储后台传来的sessionId,路由跳转时进行判断
//service.js
export const login = (params) => axios.post(url, params);
//login.vue
import {login} from './service'
import {setCookies} from './utils' //公共方法
export default{
data(){
return {...};
},
created(){
this.init();
},
methods:{
init(){
login(this.userInfoObject).then(res => {
if(res.msg === "success"){
setCookie("sessionId", res.data);//存储sessionId
this.$messsage.success("登录成功!");
this.$router.push("/main");//路由跳转
}else{
this.$messsage.success("登录失败!")
}
})
}
}
}
在导航守卫内判断的时候:
//router.js
import {getCookie} from './utils'
const router = new Router({
.......
});
router.beforeEach( (to, from, next) => {
if(!getCookie("sessionId")){
next('/login') //跳转主页
}else{
next(); //直接跳转目标路由
}
})
export {router}
10
相似问题