Vue 使用beforeEach实现登录状态检查功能
时间:2020-10-15 23:15:38|栏目:vue|点击: 次
使用VueRouter的beforeEach钩子函数,可以实现导航跳转前检查登录状态的需求。
1.在登录请求接口时返回用户的信息,比如 userInfo:{userId:'123', userName:'小明'},登录成功之后将userInfo存入store中。
2.使用beforeEach实现登录状态检查
vueRouter.beforeEach((to, from, next) => {
//store的getters中定义获取用户信息的函数 getUser
//userId为空说明用户未登录
let isLogin = store.getters.getUser.userId;
if (!isLogin) {//未登录
if (to.path !== '/login') {//跳转到登录页
return next({path: '/login'});
}else {
next();
}
}else {//已登录
if (to.path === '/login') {//跳转到首页
return next({path: '/index'});
}
next();
}
});
如果需要退出登录,只需要将保存在store中的用户信息置空即可。
上一篇:vue.js使用v-model实现表单元素(input) 双向数据绑定功能示例
栏 目:vue
本文标题:Vue 使用beforeEach实现登录状态检查功能
本文地址:http://www.codeinn.net/misctech/11608.html






