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

相关推荐
糖拌西瓜皮9 小时前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
智通1 天前
Node.js事件循环核心机制
node.js
初圣魔门首席弟子1 天前
Node.js 详细介绍(知识库版)
windows·qt·node.js·知识库
糖拌西瓜皮1 天前
Java 开发者如何快速上手 Node.js:一份从入门到进阶的学习路线
node.js
yspwf1 天前
NestJS 配置管理完整方案
后端·架构·node.js
网络点点滴1 天前
Node.js事件驱动架构
架构·node.js
weixin_471383031 天前
Node.js + Express 入门实战笔记-01-基础
node.js·lua·express
Rain5092 天前
2.2 数据基础:数据库集成与 ORM(TypeORM / Prisma)
数据库·人工智能·ai·数据分析·node.js·自动化·ai编程
大家的林语冰2 天前
npm 不忍了,正式上线“阶段式发布“的新功能,进一步对抗频繁的供应链攻击!
前端·javascript·node.js
天蓝色的鱼鱼2 天前
Node.js 现在能直接跑 TypeScript 了,tsx 和 ts-node 还需要吗?
前端·typescript·node.js