Flyinsky's Codes
463 字
2 分钟
Vue3WithVite/基于Router的拦截未登陆用户重定向
2024-09-24
在web 应用中,如果用户可以在未登陆的状态下访问任意页面,或者访问不具有访问权限的页面,可能会引发一些无法想象的错误,今天我们通过路由守卫功能来对其进行拦截。

​ 首先写一个pinia store来存储登陆用户的信息,未登陆下默认为null。

​ 里面包含一个登陆,一个登出。对user对象的写入和抹去。

import {defineStore} from "pinia"; const useUserStore = defineStore('user', { state: () => ({ user: null }), action: { login(user) { this.user = user; }, logout() { this.user = null } } })

​ 第二就是在路由js中添加以下函数:

大致内容为,将允许公开访问的页面存入Map,基于Map的特性我们可以直接查询到前往的路径是否为公开路径中的成员,如果是就放行。其次我们对路径进行检查,如果有未知路径则重定向到404页面。如果userStore中的用户为null先向用户获取个人信息接口请求,如果后端返回没有登陆状态则说明用户真的没有登陆过,则将其重定向到验证页面。

router.beforeEach((to, from, next) => { const userStore = useUserStore() const publicMap = new Map() publicMap.set('/', 1) publicMap.set('/auth', 2) publicMap.set('/test', 3) publicMap.set('/error/401', 4) publicMap.set('/error/404', 5) // 检查要访问的路径是否是根路径 if (to.matched.length === 0) next('error/404') if (to.meta.title) { document.title = 'MetaMind' } else { document.title = to.meta.title } if (!publicMap.has(to.path)) { // 不是访问根路径,检查用户状态 const user = userStore.user; // 假设你的用户状态保存在Vuex的`user`状态中 if (user === null) { get('api/user/me', (message) => { userStore.login(message); next(); }, () => { next('/error/401'); // 3秒后重定向到根路径 }, () => { } ) } else { // 用户已登录,允许路由继续 next(); } } else { // 访问的是根路径,直接放行 next(); } })