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 小时前
工作流都公开了,为什么还不能继承 Owner 权限?
javascript·人工智能·node.js
冲冲14 小时前
nvm-windows的安装
node.js
秋秋小事17 小时前
LangChain的核心概念与生态
node.js
翼龙云_cloud20 小时前
阿里云国际服务器代理商:ECS 快速部署 Node.js 项目实战指南
服务器·阿里云·node.js
FEF前端团队2 天前
小程序微信支付 V3 接入实战手册:从商户配置到前后端落地
javascript·后端·node.js
万敏2 天前
Vue3 全栈实战第七周:错误处理与请求层封装实战记录
vue.js·node.js·全栈
AD_youyu2 天前
Node.js 安装教程
node.js
m0_380743872 天前
为 OpenAI 兼容接口配置教程
开发语言·python·node.js
__zRainy__2 天前
Node系列 · ORM:Sequelize 简介
数据库·后端·node.js
水獭比特2 天前
工具都批准了,为什么还不能执行?给 Agent 补上第二道校验
javascript·人工智能·node.js