前言:
在uniapp 使用中,对于登录界面可能需要路由守卫进行方便判断跳转,以下有两种方案,可以判断用户跳转的时候是否是登录状态
方案一:
1. 可以使用插件 hh-router-guard

- 使用 uni-simpe-route

方案二: 使用通过uni提供的拦截器实现, uni.addInterceptor
1.新建interceptor.js
javascript
// ====================== 全局路由拦截器 ======================
// 功能:统一管理路由拦截逻辑(仅使用白名单模式)
// 使用:在 App.vue 的 onLaunch 中调用 initRouteGuard()
// 1. 核心配置(支持动态更新)
const routeConfig = {
// 白名单:完全开放的页面路径
whiteList: new Set([
'/modules/login/index',
'/pages/error/404'
]),
// 动态扩展名单(可从接口加载)
dynamicList: new Set()
};
// 2. 权限校验逻辑
function checkPermission(url) {
const path = url.split('?')[0];
console.log('path', path)
// 白名单校验
if (routeConfig.whiteList.has(path)) {
console.log('放行白名单')
return true; // 放行白名单页面
}
// 默认拦截非白名单页面,跳转到登录页
//!! 如果tokne存在且有效,返回true ,否则返回fasle
const token = uni.getStorageSync('token');
console.log('token', token)
return !!uni.getStorageSync('token'); // 检查登录状态
}
// 3. 拦截器核心方法
const routeInterceptor = {
invoke(args) {
console.log('启用拦截器', args);
if (checkPermission(args.url)) return true;
// 未登录跳转登录页(携带来源路径)
uni.redirectTo({
url: `/modules/login/index?redirect=${encodeURIComponent(args.url)}`
});
return false; // 阻断原始跳转
}
};
// 4. 初始化方法(暴露给外部调用)
export function initRouteGuard() {
// 注册拦截器(覆盖主要路由方法)
uni.addInterceptor('navigateTo', routeInterceptor);
uni.addInterceptor('redirectTo', routeInterceptor);
uni.addInterceptor('reLaunch', routeInterceptor);
console.log('[路由守卫] 已启动');
}
// 5. 动态更新白名单方法
export function updateRouteConfig(paths, isReset = false) {
// 如果需要重置白名单,先清空
if (isReset) routeConfig.whiteList.clear();
// 添加新的路径到白名单
paths.forEach(path => routeConfig.whiteList.add(path));
console.log(`[路由守卫] 已更新白名单:${paths.join(', ')}`);
}
// 6. 扩展:角色权限校验(可选)
export function checkUserRole(requiredRole) {
const userRole = uni.getStorageSync('userRole') || 'guest';
return userRole === requiredRole;
}
- 在app.vue onLaunch中调用 initRouteGuard(); // 启动拦截器