uniapp小程序添加路由全局限制,增加路由白名单,登录后接口跳转参数正常传递

uniapp小程序添加路由全局限制,增加路由白名单,登录后接口跳转参数正常传递

** 组件存放的位置 /utils/router.js**

复制代码
import pagesJson from '@/pages.json'; // 引用配置文件的tabbar配置信息
const tabBarListData = pagesJson.tabBar.list
// 路由白名单
const whiteList = [
  '/pages/index/index',
  '/pages/mine/index',
  '/pages/login/index'
]

// tabBar 页面路径
const tabBarList =  tabBarListData.map(item => `/${item.pagePath}`)

// 保存原始路由方法
const originalNavigateTo = uni.navigateTo
const originalRedirectTo = uni.redirectTo
const originalSwitchTab = uni.switchTab
const originalNavigateBack = uni.navigateBack

// 路由拦截处理
function routerInterceptor(args) {
  return new Promise((resolve) => {
    let url = args.url
    if (!url) return resolve(true)

    // 1. 获取当前要跳转的路径(不带参数)
    const toPath = url.split('?')[0]

    // 2. 白名单直接放行
    if (whiteList.includes(toPath)) {
      return resolve(true)
    }

    // 3. 判断是否登录
    const token = uni.getStorageSync('token')
    if (!token) {
      // 未登录 → 存起来跳转目标,登录后自动回去
      uni.setStorageSync('redirectUrl', url)
      
      // 跳转登录页
      uni.redirectTo({
        url: '/pages/login/login'
      })
      return resolve(false)
    }

    // 4. 已登录 → 放行
    resolve(true)
  })
}

// 开始全局拦截
uni.navigateTo = async function(options) {
  const canGo = await routerInterceptor(options)
  if (canGo) originalNavigateTo.call(this, options)
}

uni.redirectTo = async function(options) {
  const canGo = await routerInterceptor(options)
  if (canGo) originalRedirectTo.call(this, options)
}

// 拦截 tabBar
uni.switchTab = async function(options) {
  const canGo = await routerInterceptor(options)
  if (canGo) originalSwitchTab.call(this, options)
}

uni.navigateBack = async function(options) {
  originalNavigateBack.call(this, options)
}

使用方法
在 App.vue 引入(必须)

复制代码
<script>
// 引入全局路由拦截
import '@/utils/router.js'

export default {
  onLaunch() {
    console.log('小程序启动')
  }
}
</script>
相关推荐
游九尘4 小时前
JavaScript 实现三段式版本号对比函数(app升级用)
javascript·uni-app
2501_916007475 小时前
前端开发常用软件与工具全面指南
android·ios·小程序·https·uni-app·iphone·webview
2501_915909069 小时前
iOS应用性能优化:十大策略提升用户体验与开发效率
android·ios·小程序·https·uni-app·iphone·webview
2601_9567436812 小时前
上海小程序开发公司技术选型指南:Serverless架构如何影响交付质量与长期成本
云原生·小程序·架构·serverless·开发经验·上海
silvia_Anne14 小时前
微信小程序之渲染商品列表
微信小程序·小程序
万能小林子15 小时前
如何将网页在线转APP?5种打包工具对比速成指南(含在线/手机/电脑方案)
android·ios·uni-app·web app·wap2app·app打包·app封装
海兰1 天前
【文字三国志:第六篇】天命重构,UI组件设计细节
人工智能·ui·语言模型·小程序
草根站起来1 天前
微信小程序request net:ERR_CERT_DATE_INVALID
微信小程序·小程序
小北的AI科技分享2 天前
广州小程序平台推荐:2026年本地商家数字化选型深度测评
小程序·广州小程序平台
MageGojo2 天前
10 种主题随机诗词:一个 API 解决小程序的诗词内容源
python·小程序·古诗词·api 接入