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

相关推荐
受打击无法动弹10 小时前
Window 10部署openclaw报错node.exe : npm error code 128
npm·node.js·openclaw
全马必破三1 天前
Webpack知识点汇总
前端·webpack·node.js
NEXT061 天前
CommonJS 与 ES Modules的区别
前端·面试·node.js
YuMiao1 天前
把 WebSocket 服务迁移到 Cloudflare Durable Objects —— 以一次协同编辑实战为例
javascript·node.js
belldeep2 天前
nodejs:如何使用 express markdown-it 实现指定目录下 Md 文件的渲染
node.js·express·markdown
未名编程2 天前
Linux / macOS / Windows 一条命令安装 Node.js + npm(极限一行版大全)
linux·macos·node.js
Go_Zezhou3 天前
pnpm下载后无法识别的问题及解决方法
开发语言·node.js
盖头盖4 天前
【vm沙箱逃逸】
node.js
belldeep4 天前
nodejs: 能在线编辑 Markdown 文档的 Web 服务程序,更多扩展功能
前端·node.js·markdown·mermaid·highlight·katax
松树戈4 天前
【vfox教程】一、vfox在win系统下的安装与卸载
jdk·node.js·vfox