Files
hmc_gbhd/frontend/src/utils/routerInterceptor.js
T
2025-04-30 14:00:38 +08:00

130 lines
3.6 KiB
JavaScript

import {Dialog} from "tdesign-mobile-vue";
import {useRequest} from "@/utils/request";
import {useUserStore} from "@/store";
/**
* 路由拦截器配置
* @param {Array} whiteList - 不需要登录就可以访问的页面路径列表
*/
export const setupRouterInterceptor = (whiteList = []) => {
// 添加各种导航方法的拦截器
addNavigationInterceptors(whiteList)
}
export const checkAuth = async () => {
if (process.env.VUE_APP_PLATFORM === 'h5' && window.location.pathname !== '/') {
const path = window.location.pathname.replace(/^\//, '')
if (!getDefaultWhiteList().includes(path)) {
const token = uni.getStorageSync('token')
if (token) {
await useUserStore().getUserInfo()
} else {
await uni.redirectTo({
url: '/pages/login/index'
})
}
}
}
}
/**
* 添加所有导航方法的拦截器
* @param {Array} whiteList - 白名单页面列表
*/
function addNavigationInterceptors(whiteList) {
// 页面跳转拦截
uni.addInterceptor('navigateTo', {
invoke: (args) => routeInterceptor(args, whiteList)
})
// 页面重定向拦截
uni.addInterceptor('redirectTo', {
invoke: (args) => routeInterceptor(args, whiteList)
})
// 页面重启动拦截
uni.addInterceptor('reLaunch', {
invoke: (args) => routeInterceptor(args, whiteList)
})
// Tab切换拦截
uni.addInterceptor('switchTab', {
invoke: (args) => routeInterceptor(args, whiteList)
})
}
/**
* 路由拦截处理函数
* @param {Object} args - 导航参数
* @param {Array} whiteList - 白名单页面列表
* @returns {Object|boolean} - 继续导航或阻止导航
*/
async function routeInterceptor(args, whiteList) {
// 获取目标路径
const token = uni.getStorageSync('token')
const targetUrl = args.url
let isInWhiteList = targetUrl === '/'
if (!isInWhiteList) {
// 检查目标路径是否在白名单中
isInWhiteList = whiteList.some(path => {
return targetUrl.startsWith(path) || targetUrl === path
})
}
console.log('路由拦截检查:', {url: targetUrl, isInWhiteList, hasToken: !!token})
// 如果不在白名单且未登录,则跳转到登录页
if (!isInWhiteList) {
if (token) {
// 获取用户信息
const user = useUserStore().userInfo
if (user == null) {
await useUserStore().getUserInfo()
}
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
}
/**
* 获取白名单页面配置
* @returns {Array} 默认白名单页面列表
*/
export const getDefaultWhiteList = () => {
return [
'/pages/index/index',
'/pages/login/index'
]
}