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(); // 启动拦截器
相关推荐
愚公搬代码10 分钟前
【愚公系列】《Web应用安全》010-Repeater模块的使用
前端·安全
Cache技术分享35 分钟前
503. Java 反射 - 编写 ServiceFactory 类
前端·后端
赵大仁42 分钟前
AI 限流 UX 设计:排队、降级、告知与用户预期管理
前端·ai·限流·用户体验·产品设计
__sjfzllv___1 小时前
在职前端Leader学习/转行 AI Agent -DAY37
前端
用户2181697049301 小时前
Flutter (二十二) GlobalKey
前端
用户2181697049301 小时前
Flutter (二十一) 下拉刷新,加载更多
前端
IT_陈寒2 小时前
Python装饰器把我坑惨了,原来这样用才不掉链子
前端·人工智能·后端
程序员爱钓鱼2 小时前
Rust Associated Type关联类型详解:为Trait定义内部类型
前端·后端·rust
zh_xuan3 小时前
个人主页左侧菜单支持分组,以及菜单显示和隐藏
前端·javascript·css
Emily156853598706 小时前
Emerson 1C31129G03 Analog Input Module
java·开发语言·前端·plc·emerson·1c31129g03·input module