2024-03-27 17:20:05 +08:00
|
|
|
|
/**
|
|
|
|
|
* by 菲鸽 on 2024-03-06
|
|
|
|
|
* 路由拦截,通常也是登录拦截
|
|
|
|
|
* 可以设置路由白名单,或者黑名单,看业务需要选哪一个
|
|
|
|
|
* 我这里应为大部分都可以随便进入,所以使用黑名单
|
|
|
|
|
*/
|
|
|
|
|
import { useUserStore } from '@/store'
|
2024-12-31 12:18:17 +08:00
|
|
|
|
import { needLoginPages as _needLoginPages, getNeedLoginPages } from '@/utils'
|
2024-03-27 17:20:05 +08:00
|
|
|
|
|
|
|
|
|
// TODO Check
|
|
|
|
|
const loginRoute = '/pages/login/index'
|
|
|
|
|
|
|
|
|
|
const isLogined = () => {
|
|
|
|
|
const userStore = useUserStore()
|
|
|
|
|
return userStore.isLogined
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const isDev = import.meta.env.DEV
|
|
|
|
|
|
|
|
|
|
// 黑名单登录拦截器 - (适用于大部分页面不需要登录,少部分页面需要登录)
|
|
|
|
|
const navigateToInterceptor = {
|
|
|
|
|
// 注意,这里的url是 '/' 开头的,如 '/pages/index/index',跟 'pages.json' 里面的 path 不同
|
|
|
|
|
invoke({ url }: { url: string }) {
|
2024-04-17 15:32:15 +08:00
|
|
|
|
// console.log(url) // /pages/route-interceptor/index?name=feige&age=30
|
2024-03-27 17:20:05 +08:00
|
|
|
|
const path = url.split('?')[0]
|
|
|
|
|
let needLoginPages: string[] = []
|
|
|
|
|
// 为了防止开发时出现BUG,这里每次都获取一下。生产环境可以移到函数外,性能更好
|
|
|
|
|
if (isDev) {
|
|
|
|
|
needLoginPages = getNeedLoginPages()
|
|
|
|
|
} else {
|
|
|
|
|
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
|
|
|
|
}
|
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)
|
2024-03-27 17:20:05 +08:00
|
|
|
|
},
|
|
|
|
|
}
|