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

相关推荐
FungLeo15 小时前
成为全栈·Node 后端篇·容器化:给 Node 应用写一个像样的 Dockerfile
docker·node.js·dockerfile·成为全栈·后端服务容器·docker 容器
WeiXin_DZbishe19 小时前
基于springboot大学生提问箱系统-计算机毕设【课程设计】72593
javascript·vue.js·spring boot·vscode·python·node.js·php
xixiaoyunya1 天前
Docker 容器化部署实战:从零搭建一套完整的 Nginx + Node.js + MySQL + Redis 项目环境
nginx·docker·node.js
晴天161 天前
npm install -f(--force)深度解析:作用原理、报错根源与风险避坑指南
前端·npm·node.js
还是大剑师兰特1 天前
Swagger 在 Node.js 项目中的安装和完整使用方法
node.js
FungLeo1 天前
成为全栈·Node 后端篇·全文搜索:从 LIKE 到全文索引
node.js·全文索引·模糊搜索·全文搜索·成为全栈·like 搜索
倾颜2 天前
AI Chat 长会话性能实践:消息虚拟化、动态高度与流式滚动设计
前端·react.js·node.js
FungLeo2 天前
成为全栈·Node 后端篇·接口文档自动化:让 OpenAPI 与代码不脱节
node.js·openapi·成为全栈·接口文档自动化
右耳朵猫AI2 天前
Node.js周刊2026W36 | NestJS 12发布、Remix 3 RC、pnpm 12 Rust重写、Node.js 26.8.0
开发语言·rust·node.js
www_aiyuanma_vip2 天前
实验室设备借用系统
node.js