vue拦截器实现登陆管控
时间: 2023-06-29 21:18:39 浏览: 124
Vue拦截器可以用于实现登录管控,具体实现方式如下:
- 定义路由拦截器:在路由跳转时,判断用户是否已经登录,如果未登录,则跳转到登录页面,否则继续访问目标页面。
router.beforeEach((to, from, next) => {
const isLogin = sessionStorage.getItem('isLogin') || false;
if (to.meta.requireAuth) {
// 判断用户是否已登录
if (isLogin) {
next();
} else {
// 跳转到登录页面
next({
path: '/login',
query: { redirect: to.fullPath }
});
}
} else {
next();
}
});
- 在登录时,设置登录状态:将用户登录状态保存在sessionStorage中。
// 登录操作
login() {
// 向后台发送登录请求
axios.post('/api/login', {
username: this.username,
password: this.password
}).then(res => {
// 登录成功,保存登录状态
sessionStorage.setItem('isLogin', true);
// 跳转到首页
this.$router.push({ path: '/' });
}).catch(err => {
console.log(err);
});
}
这样,当用户未登录时,访问需要登录的页面时会自动跳转到登录页面,登录成功后再跳转回目标页面。
相关推荐












