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

相关推荐
eRRA OFAG1 天前
Windows 上彻底卸载 Node.js
windows·node.js
❀͜͡傀儡师1 天前
Claude Code 官方弃用 npm 安装方式:原因分析与完整迁移指南
前端·npm·node.js·claude code
dgvri1 天前
Node.js使用教程
node.js·编辑器·vim
2601_949816161 天前
Node.js npm 安装过程中 EBUSY 错误的分析与解决方案
前端·npm·node.js
2601_949194261 天前
TypeScript 与后端开发Node.js
javascript·typescript·node.js
2601_949815331 天前
Node.js HTTP模块详解:创建服务器、响应请求与客户端请求
服务器·http·node.js
2601_949815841 天前
Node.js NativeAddon 构建工具:node-gyp 安装与配置完全指南
node.js
不会敲代码12 天前
手写一个「迷你 Cursor」:从零构建 AI 编程助手(LangChain + Tool Calling 实战)
langchain·node.js·cursor
不做超级小白2 天前
把图片压小,但不糊:reduceUrImgs项目关键点拆解
前端·开源·node.js
阿赛工作室2 天前
符合欧盟安全标准的 Node.js + Vue3 全栈架构设计
安全·node.js