This commit is contained in:
2025-04-29 17:58:58 +08:00
parent 095d8335ac
commit 086643b834
5 changed files with 99 additions and 61 deletions
+49 -33
View File
@@ -1,4 +1,5 @@
import {Dialog} from "tdesign-mobile-vue";
import {useRequest} from "@/utils/request";
/**
* 路由拦截器配置
@@ -41,44 +42,61 @@ function addNavigationInterceptors(whiteList) {
* @param {Array} whiteList - 白名单页面列表
* @returns {Object|boolean} - 继续导航或阻止导航
*/
function routeInterceptor(args, whiteList) {
async function routeInterceptor(args, whiteList) {
// 获取目标路径
const token = uni.getStorageSync('token')
const targetUrl = args.url
// 检查目标路径是否在白名单中
const isInWhiteList = whiteList.some(path => {
return targetUrl.startsWith(path) || targetUrl === path
})
let isInWhiteList = targetUrl === '/'
if (!isInWhiteList) {
// 检查目标路径是否在白名单中
isInWhiteList = whiteList.some(path => {
return targetUrl.startsWith(path) || targetUrl === path
})
}
console.log('路由拦截检查:', {url: targetUrl, isInWhiteList, hasToken: !!token})
// 如果不在白名单且未登录,则跳转到登录页
if (!isInWhiteList && !token) {
console.log('拦截导航,跳转到登录页')
// 保存用户尝试访问的页面,以便登录后跳回
try {
uni.setStorageSync('REDIRECT_URL', targetUrl)
} catch (e) {
}
Dialog.confirm({
title: '提示',
content: '您尚未登录,是否前往登录页面?',
cancelBtn: '取消',
confirmBtn: '确认',
onConfirm: () => {
uni.navigateTo({
url: '/pages/login/index'
})
},
onCancel: () => {
console.log('取消登录')
if (!isInWhiteList) {
if (token) {
// 获取用户信息
const {user} = getApp().globalData
if (user == null) {
const {code, data, msg} = await useRequest().get('/client/auth/info')
if (code === 0) {
getApp().globalData.user = data
return args
}
}
})
// 阻止原导航
return false
return args
} else {
console.log('拦截导航,跳转到登录页')
// 保存用户尝试访问的页面,以便登录后跳回
try {
uni.setStorageSync('REDIRECT_URL', targetUrl)
} catch (e) {
}
Dialog.confirm({
title: '提示',
content: '您尚未登录,是否前往登录页面?',
cancelBtn: '取消',
confirmBtn: '确认',
onConfirm: () => {
uni.navigateTo({
url: '/pages/login/index'
})
},
onCancel: () => {
console.log('取消登录')
}
})
// 阻止原导航
return false
}
}
// 继续原导航
return args
@@ -90,9 +108,7 @@ function routeInterceptor(args, whiteList) {
*/
export const getDefaultWhiteList = () => {
return [
'/',
'/pages/index/index',
'/pages/login/index',
'/pages/profile/index'
'/pages/login/index'
]
}