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

相关推荐
郏国上2 小时前
查询数据库上所有表用到图片和视频的数据,并记录到excel表
mongodb·node.js·excel
Q_Q5110082853 小时前
python+django/flask+vue的书城图书阅读器系统,亮点含目录章节pycharm
spring boot·python·django·flask·node.js·php
Q_Q5110082857 小时前
python+django/flask的图书馆管理系统vue
spring boot·python·django·flask·node.js·php
Q_Q5110082857 小时前
python+django/flask的美食交流宣传系统vue
spring boot·python·pycharm·django·flask·node.js·php
Q_Q5110082857 小时前
python+django/flask+vue的基层智能化人员调度系统pycharm-计算机毕业设计
spring boot·python·pycharm·django·flask·node.js
jenchoi4138 小时前
软件供应链npm/pypi投毒预警情报【2025-11-09】
前端·安全·web安全·网络安全·npm·node.js
百***416619 小时前
node.js+npm的环境配置以及添加镜像(保姆级教程)
arcgis·npm·node.js
百***416619 小时前
2024最新版Node.js下载安装及环境配置教程【保姆级】
node.js
Q_Q196328847521 小时前
python+django/flask的医院财务管理系统
spring boot·python·django·flask·node.js
cmdyu_21 小时前
修复mac系统下node22安装模块报fatal error: ‘memory‘ file not found错误的问题
macos·npm·node.js