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

相关推荐
赖龙3 小时前
pnpm vs npm
前端·npm·node.js
烂蜻蜓16 小时前
Node.js入门教程(三十一):Express 框架
node.js·express
小屁孩你滑稽掉了17 小时前
prisma操作数据库的方法使用教程(简洁版)
数据库·node.js·prisma·fastify
__zRainy__18 小时前
Node系列 · Node基础:https 模块
后端·网络协议·http·https·node.js
__zRainy__1 天前
Node.js Web 框架选型指南:从 Express 到 Hono 的全景对比
前端·node.js·express·koa·nestjs·egg·fastify
烂蜻蜓1 天前
Node.js入门教程(二十八):GET/POST请求
node.js
__zRainy__1 天前
Node系列 · Node基础:net 模块
后端·node.js
嘟嘟07172 天前
从浏览器到 hello world:Docker + nginx 反向代理 + Node 最小服务器一次讲清
docker·容器·node.js
禁止摆烂_才浅2 天前
Node.js 高频面试题
前端·面试·node.js
FungLeo2 天前
Node 后端实战 · 老系统数据迁移怎么不出乱子?V1→V2 重构实战与 3 个生产坑
node.js·serverless·数据库迁移·d1 数据库