前言:?
在uniapp 使用中,對于登錄界面可能需要路由守衛進行方便判斷跳轉,以下有兩種方案,可以判斷用戶跳轉的時候是否是登錄狀態?
方案一:?
1. 可以使用插件? hh-router-guard
2. 使用 uni-simpe-route
方案二: 使用通過uni提供的攔截器實現, uni.addInterceptor
1.新建interceptor.js?
// ====================== 全局路由攔截器 ======================
// 功能:統一管理路由攔截邏輯(僅使用白名單模式)
// 使用:在 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;
}
2. 在app.vue? onLaunch中調用?? ?initRouteGuard(); // 啟動攔截器