route.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * by 菲鸽 on 2024-03-06
  3. * 路由拦截,通常也是登录拦截
  4. * 可以设置路由白名单,或者黑名单,看业务需要选哪一个
  5. * 我这里应为大部分都可以随便进入,所以使用黑名单
  6. */
  7. import { useUserStore } from '@/store'
  8. import { needLoginPages as _needLoginPages, getNeedLoginPages, getLastPage } from '@/utils'
  9. // TODO Check
  10. const loginRoute = '/pages/login/index'
  11. const isLogined = () => {
  12. const userStore = useUserStore()
  13. return userStore.isLogined
  14. }
  15. const isDev = import.meta.env.DEV
  16. // 黑名单登录拦截器 - (适用于大部分页面不需要登录,少部分页面需要登录)
  17. const navigateToInterceptor = {
  18. // 注意,这里的url是 '/' 开头的(也有可能是相对路径),如 '/pages/index/index',跟 'pages.json' 里面的 path 不同
  19. invoke({ url }: { url: string }) {
  20. // console.log(url) // /pages/route-interceptor/index?name=feige&age=30
  21. let path = url.split('?')[0]
  22. // 处理相对路径
  23. if (!path.startsWith('/')) {
  24. const currentPath = getLastPage().route
  25. const normalizedCurrentPath = currentPath.startsWith('/') ? currentPath : `/${currentPath}`
  26. const baseDir = normalizedCurrentPath.substring(0, normalizedCurrentPath.lastIndexOf('/'))
  27. path = `${baseDir}/${path}`
  28. }
  29. let needLoginPages: string[] = []
  30. // 为了防止开发时出现BUG,这里每次都获取一下。生产环境可以移到函数外,性能更好
  31. if (isDev) {
  32. needLoginPages = getNeedLoginPages()
  33. } else {
  34. needLoginPages = _needLoginPages
  35. }
  36. const isNeedLogin = needLoginPages.includes(path)
  37. if (!isNeedLogin) {
  38. return true
  39. }
  40. const hasLogin = isLogined()
  41. if (hasLogin) {
  42. return true
  43. }
  44. const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
  45. uni.navigateTo({ url: redirectRoute })
  46. return false
  47. },
  48. }
  49. export const routeInterceptor = {
  50. install() {
  51. uni.addInterceptor('navigateTo', navigateToInterceptor)
  52. uni.addInterceptor('reLaunch', navigateToInterceptor)
  53. uni.addInterceptor('redirectTo', navigateToInterceptor)
  54. uni.addInterceptor('switchTab', navigateToInterceptor)
  55. },
  56. }