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

相关推荐
集成显卡11 小时前
基于 Node.js 的 API 方式接入深度求索Deepseek、字节跳动豆包大模型
前端·人工智能·node.js
HexCIer12 小时前
cbT.js: 一个让模板继承变得优雅的 Node.js 模板引擎
javascript·node.js
Q_Q51100828515 小时前
python的小学课外综合管理系统
开发语言·spring boot·python·django·flask·node.js
ChongYu重玉17 小时前
【node/vue】css制作可3D旋转倾斜的图片,朝向鼠标
javascript·css·vue.js·经验分享·笔记·node.js·vue
前端双越老师18 小时前
使用 langChain.js 实现 RAG 知识库语义搜索
人工智能·langchain·node.js
植物昂光18 小时前
基于Node.js的微博热榜抓取与展示开发记录
前端·node.js
今天也在写bug19 小时前
输入npm install后发生了什么
前端·npm·node.js
popoxf1 天前
在新版本的微信开发者工具中使用npm包
前端·npm·node.js
Q_Q19632884751 天前
python的平安驾校管理系统
开发语言·spring boot·python·django·flask·node.js·php
GISer_Jing1 天前
LLM对话框项目总结II
前端·javascript·node.js