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

相关推荐
墨菲安全5 小时前
NPM组件 betsson 等窃取主机敏感信息
前端·npm·node.js·软件供应链安全·主机信息窃取·npm组件投毒
csdn_aspnet15 小时前
Node.js 使用 WebSockets 和 Socket.IO 实现实时聊天应用程序
node.js
whhhhhhhhhw19 小时前
Node.js核心API(fs篇)
node.js
聪聪的学习笔记19 小时前
【1】确认安装 Node.js 和 npm版本号
前端·npm·node.js
GDAL1 天前
Node.js v22.5+ 官方 SQLite 模块全解析:从入门到实战
数据库·sqlite·node.js
RunsenLIu1 天前
基于Vue.js + Node.js + MySQL实现的图书销售管理系统
vue.js·mysql·node.js
Allen_zx1 天前
Elpis - 基于 Koa + Vue3 的企业级全栈应用框架
node.js
鹏程1 天前
局域网下五子棋,html+node.js实现
node.js·html
爱分享的程序员1 天前
前端面试专栏-算法篇:17. 排序算法
前端·javascript·node.js
盛夏绽放1 天前
接口验证机制在Token认证中的关键作用与优化实践
前端·node.js·有问必答