interceptor.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * by 菲鸽 on 2024-03-06
  3. * 路由拦截,通常也是登录拦截
  4. * 可以设置路由白名单,或者黑名单,看业务需要选哪一个
  5. * 我这里应为大部分都可以随便进入,所以使用黑名单
  6. */
  7. import { useUserStore } from '@/store'
  8. import { tabbarStore } from '@/tabbar/store'
  9. import { getLastPage } from '@/utils'
  10. import { EXCLUDE_LIST, LOGIN_PAGE_LIST } from '../login/config'
  11. // 黑名单登录拦截器 - (适用于大部分页面不需要登录,少部分页面需要登录)
  12. export const navigateToInterceptor = {
  13. // 注意,这里的url是 '/' 开头的,如 '/pages/index/index',跟 'pages.json' 里面的 path 不同
  14. // 增加对相对路径的处理,BY 网友 @ideal
  15. invoke({ url }: { url: string }) {
  16. console.log(url) // /pages/route-interceptor/index?name=feige&age=30
  17. let path = url.split('?')[0]
  18. // 处理相对路径
  19. if (!path.startsWith('/')) {
  20. const currentPath = getLastPage()?.route || ''
  21. const normalizedCurrentPath = currentPath.startsWith('/') ? currentPath : `/${currentPath}`
  22. const baseDir = normalizedCurrentPath.substring(0, normalizedCurrentPath.lastIndexOf('/'))
  23. path = `${baseDir}/${path}`
  24. }
  25. if (LOGIN_PAGE_LIST.includes(path)) {
  26. console.log('000')
  27. return
  28. }
  29. tabbarStore.restorePrevIdx()
  30. console.log('拦截器中得到的 path:', path)
  31. const userStore = useUserStore()
  32. if (userStore.hasLogin || [...EXCLUDE_LIST, ...LOGIN_PAGE_LIST].includes(path)) {
  33. console.log('111')
  34. uni.navigateTo({ url: path })
  35. return
  36. }
  37. console.log('222')
  38. const redirectUrl = `/pages/login/login?redirect=${encodeURIComponent(path)}`
  39. uni.navigateTo({ url: redirectUrl })
  40. },
  41. }
  42. export const routeInterceptor = {
  43. install() {
  44. uni.addInterceptor('navigateTo', navigateToInterceptor)
  45. uni.addInterceptor('reLaunch', navigateToInterceptor)
  46. uni.addInterceptor('redirectTo', navigateToInterceptor)
  47. uni.addInterceptor('switchTab', navigateToInterceptor)
  48. },
  49. }