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

78 lines
2.7 KiB
TypeScript
Raw Normal View History

2024-03-27 17:20:05 +08:00
/**
* by on 2024-03-06
*
*
* 便使
*/
import { useUserStore } from '@/store'
import { tabbarStore } from '@/tabbar/store'
import { needLoginPages as _needLoginPages, getLastPage, getNeedLoginPages } from '@/utils'
2024-03-27 17:20:05 +08:00
// TODO Check
const loginRoute = import.meta.env.VITE_LOGIN_URL
2024-03-27 17:20:05 +08:00
function isLogined() {
2024-03-27 17:20:05 +08:00
const userStore = useUserStore()
return !!userStore.userInfo.username
2024-03-27 17:20:05 +08:00
}
const isDev = import.meta.env.DEV
// 黑名单登录拦截器 - (适用于大部分页面不需要登录,少部分页面需要登录)
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 }) {
2024-04-17 15:32:15 +08:00
// 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}`
}
2024-03-27 17:20:05 +08:00
let needLoginPages: string[] = []
// 为了防止开发时出现BUG这里每次都获取一下。生产环境可以移到函数外性能更好
if (isDev) {
needLoginPages = getNeedLoginPages()
}
else {
2024-03-27 17:20:05 +08:00
needLoginPages = _needLoginPages
}
2024-04-17 15:32:15 +08:00
const isNeedLogin = needLoginPages.includes(path)
if (!isNeedLogin) {
return true
}
const hasLogin = isLogined()
if (hasLogin) {
return true
2024-03-27 17:20:05 +08:00
}
tabbarStore.restorePrevIdx()
2024-04-17 15:32:15 +08:00
const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
uni.navigateTo({ url: redirectRoute })
return false
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)
// #ifdef H5
// 一个粗糙的实现方式不满意可以自行修改https://github.com/unibest-tech/unibest/issues/192
// H5环境路由拦截监听hashchange事件
window.addEventListener('hashchange', () => {
// 获取当前路径
const currentPath = `/${window.location.hash.split('#/')[1]?.split('?')[0]}`
navigateToInterceptor.invoke({ url: currentPath })
})
// #endif
2024-03-27 17:20:05 +08:00
},
}