Files
aiot-uniapp/src/router/interceptor.ts

60 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-03-27 17:20:05 +08:00
/**
* by on 2024-03-06
*
*
* 便使
*/
import { useUserStore } from '@/store'
import { getLastPage } from '@/utils'
import { EXCLUDE_LIST, LOGIN_PAGE_LIST } from '../login/config'
2024-03-27 17:20:05 +08:00
// 黑名单登录拦截器 - (适用于大部分页面不需要登录,少部分页面需要登录)
export const navigateToInterceptor = {
2025-04-28 18:18:12 +08:00
// 注意这里的url是 '/' 开头的,如 '/pages/index/index',跟 'pages.json' 里面的 path 不同
// 增加对相对路径的处理BY 网友 @ideal
2024-03-27 17:20:05 +08:00
invoke({ url }: { url: string }) {
console.log(url) // /pages/route-interceptor/index?name=feige&age=30
let path = url.split('?')[0]
// 处理相对路径
if (!path.startsWith('/')) {
const currentPath = getLastPage()?.route || ''
const normalizedCurrentPath = currentPath.startsWith('/') ? currentPath : `/${currentPath}`
const baseDir = normalizedCurrentPath.substring(0, normalizedCurrentPath.lastIndexOf('/'))
path = `${baseDir}/${path}`
}
if (LOGIN_PAGE_LIST.includes(path)) {
console.log('000')
return
2024-03-27 17:20:05 +08:00
}
const userStore = useUserStore()
if (userStore.hasLogin) {
return
}
// tabbarStore.restorePrevIdx()
console.log('拦截器中得到的 path:', path, userStore.hasLogin)
if ([...EXCLUDE_LIST, ...LOGIN_PAGE_LIST].includes(path)) {
console.log('111')
uni.navigateTo({ url: path })
return
}
console.log('222')
const redirectUrl = `/pages/login/login?redirect=${encodeURIComponent(path)}`
uni.navigateTo({ url: redirectUrl })
2024-03-27 17:20:05 +08:00
},
}
export const routeInterceptor = {
install() {
uni.addInterceptor('navigateTo', navigateToInterceptor)
uni.addInterceptor('reLaunch', navigateToInterceptor)
uni.addInterceptor('redirectTo', navigateToInterceptor)
2024-12-31 12:18:17 +08:00
uni.addInterceptor('switchTab', navigateToInterceptor)
2024-03-27 17:20:05 +08:00
},
}