Vue中如何通过beforeEach钩子实现登录状态的预先检查?
- 内容介绍
- 文章标签
- 相关推荐
本文共计282个文字,预计阅读时间需要2分钟。
使用VueRouter的beforeEach钩子函数,可以实现导航跳转前的登录状态检查需求。具体操作如下:
1. 在登录请求接口时,返回用户信息,例如:userInfo: {userId: '123', userName: '小明'}。
2.登录成功后,将userInfo存储到sessionStorage中。
3.在路由守卫beforeEach中,检查sessionStorage中是否有userInfo,如果没有,则重定向到登录页面。
使用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 使用beforeEach实现登录状态检查功能就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。
本文共计282个文字,预计阅读时间需要2分钟。
使用VueRouter的beforeEach钩子函数,可以实现导航跳转前的登录状态检查需求。具体操作如下:
1. 在登录请求接口时,返回用户信息,例如:userInfo: {userId: '123', userName: '小明'}。
2.登录成功后,将userInfo存储到sessionStorage中。
3.在路由守卫beforeEach中,检查sessionStorage中是否有userInfo,如果没有,则重定向到登录页面。
使用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 使用beforeEach实现登录状态检查功能就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。

