uni-app路由拦截

新建一个auth.js

/**

* @description 权限存储函数

*/

const authorizationKey = 'Authorization'

export function getAuthorization() {

return uni.getStorageSync(authorizationKey)

}

export function setAuthorization(authorization) {

return uni.setStorageSync(authorizationKey, authorization)

}

export function removeAuthorization(authorization) {

return uni.removeStorageSync(authorizationKey)

}

新建route.js

import { getAuthorization } from '@/utils/auth.js'

// 白名单

const whiteList = [

'/', // 注意入口页必须直接写 '/'

'/pages/Login/Login'

]

export default async function() {

const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']

// 用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器

list.forEach(item => {

uni.addInterceptor(item, {

invoke(e) {

// 获取要跳转的页面路径(url去掉"?"和"?"后的参数)

const url = e.url.split('?')[0]

console.log('url', url)

// 判断当前窗口是白名单,如果是则不重定向路由

let pass

if (whiteList) {

pass = whiteList.some((item) => {

if (typeof (item) === 'object' && item.pattern) {

return item.pattern.test(url)

}

return url === item

})

}

// 不是白名单并且没有token

if (!pass && !getAuthorization()) {

uni.showToast({

title: '请先登录',

icon: 'none'

})

uni.navigateTo({

url: "/pages/Login/Login"

})

return false

}

return e

},

fail(err) { // 失败回调拦截

console.log(err)

}

})

})

}

APP.vue

import routingIntercept from '@/router/route.js'

export default {

onLaunch: function() {

console.log('App Launch');

// 对路由进行统一拦截,实现路由导航守卫 router.beforeEach 功能

routingIntercept()

},

onShow: function() {

console.log('App Show')

},

onHide: function() {

console.log('App Hide')

}

}

原文链接:https://blog.csdn.net/qq_38687592/article/details/129299566

相关推荐
行走的陀螺仪2 小时前
Vite & Webpack 插件/Loader 封装完全指南
前端·webpack·node.js·vite·前端工程化·打包构建
源去_云走3 小时前
自建 Iconfy API 服务:解决国内访问不稳定问题
前端·容器·npm·node.js
旧梦星轨8 小时前
掌握 Vite 环境配置:从 .env 文件到运行模式的完整实践
前端·前端框架·node.js·vue·react
qq_348231859 小时前
面向初学者到进阶者的 Node.js 学习指南
node.js
大猫和小黄10 小时前
Windows 下使用 NVM 管理多个 Node.js 版本
windows·node.js
Chase_______10 小时前
【保姆级】Node.js 最新安装教程,附环境变量配置
node.js
WangHappy1 天前
出海不愁!用Vue3 + Node.js + Stripe实现全球支付
前端·node.js
该用户已不存在1 天前
Node.js后端开发必不可少的7个核心库
javascript·后端·node.js
小邋遢2.01 天前
vscod 执行npm build报错:Error: Cannot find module ‘vite‘
前端·npm·node.js
孟陬1 天前
2025-12-11 之后前端 npm 如何发包 How to Publish NPM Package in Year 2025
npm·node.js·bun