Vue3 路由守卫:如何判断Token是否过期?
在Vue3中,可以使用路由导航守卫来判断token是否过期。首先,在路由配置文件中,定义一个全局前置守卫,在每次路由跳转之前进行判断:
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHistory(),
routes: [
// 路由配置
],
});
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token'); // 从localStorage中获取token
const expiration = localStorage.getItem('expiration'); // 从localStorage中获取token过期时间
// 判断token是否存在且未过期
if (token && expiration && new Date().getTime() < expiration) {
next();
} else {
// 跳转到登录页或其他处理方式
next('/login');
}
});
export default router;
在每次路由跳转之前,先从localStorage中获取token和过期时间,然后与当前时间进行比较,如果token存在且未过期,则继续跳转到目标路由;否则,跳转到登录页或其他处理方式。
这样,在每次路由跳转之前都会进行token的过期判断,保证了用户在token过期后不能正常访问需要认证的页面。
原文地址: https://www.cveoy.top/t/topic/pG61 著作权归作者所有。请勿转载和采集!