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

相关推荐
65岁退休Coder12 小时前
PI Agent 开发一个生产级 Harness
后端·node.js·agent
szephyr13 小时前
WebSocket 实战:心跳、断线重连、鉴权,一次讲清
前端·websocket·node.js·长连接·实时通信
秋秋小事14 小时前
node postgreSQL的select与include
node.js
ID346107442014 小时前
【课程设计】基于Spring Boot+Vue的游戏账号租赁系统的设计与实现-计算机毕设 附源码50345
javascript·vue.js·spring boot·python·node.js·php·课程设计
柚yuzumi15 小时前
彻底搞懂 JavaScript 类型转换:显式转换、隐式转换与 ToPrimitive
前端·javascript·node.js
cpolar技术支持19 小时前
本地登录正常,公网却掉线?Express Session 经 cpolar HTTPS 访问的 Cookie 排障实战
node.js·express·cpolar·cookie·session
秋秋小事19 小时前
node prisma+postgreSQL数据库事务
node.js
badhope21 小时前
C++、Node.js、Python 写最小 HTTP 服务谁快?我实测了 6 万次请求
node.js
console.log('npc')1 天前
03 — 核心框架:App 与中间件
后端·node.js·express
云浪1 天前
从 0 手写一个 MCP Server:让 Copilot 调用 Tool 完成四则运算
javascript·node.js·mcp