uniapp 中使用路由导航守卫,进行登录鉴权

前言:

在uniapp 使用中,对于登录界面可能需要路由守卫进行方便判断跳转,以下有两种方案,可以判断用户跳转的时候是否是登录状态

方案一:

1. 可以使用插件 hh-router-guard
  1. 使用 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;
}
  1. 在app.vue onLaunch中调用 initRouteGuard(); // 启动拦截器
相关推荐
Mh6 小时前
我是如何设计品牌站组件库的?
前端·css·设计模式
程序员大阳7 小时前
副队长Vue3教程(2)--Vite 搭建 Vue 项目,认识目录结构
前端·javascript·vue.js·vite·创建项目·目录结构·项目结构
濮水大叔7 小时前
Cabloy/Zova 与 Next.js 的 SSR 水合差异
前端·typescript·next.js
SoaringHeart7 小时前
Flutter最佳实践:用 flutter_html 渲染富文本
前端·flutter
Flynt9 小时前
Chrome给AI编程助手塞了203篇前端规范,我拆包实测:检索0.77秒是真快,扫描器有点挑食
前端·chrome·ai编程
北城笑笑9 小时前
Vue 110 ,若依SSE流式接口限次空500排查与解决
前端·javascript·vue.js·后端·vue
程序员韩星10 小时前
OpenAI 兼容接口返回 404,先查请求地址,再查模型名
前端·人工智能·http
Patrick_Wilson10 小时前
构建通过了,为什么有些浏览器还会白屏?
前端·javascript·浏览器
其实防守也摸鱼10 小时前
用 Claude Code 重构遗留系统:从评估到落地的完整指南
前端·网络·人工智能·chrome·安全·重构
七仔啊11 小时前
CNC计算机数控加工模拟器
前端