interceptor.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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_PAGE_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. if (url === undefined) {
  18. return
  19. }
  20. let path = url.split('?')[0]
  21. // 处理相对路径
  22. if (!path.startsWith('/')) {
  23. const currentPath = getLastPage()?.route || ''
  24. const normalizedCurrentPath = currentPath.startsWith('/') ? currentPath : `/${currentPath}`
  25. const baseDir = normalizedCurrentPath.substring(0, normalizedCurrentPath.lastIndexOf('/'))
  26. path = `${baseDir}/${path}`
  27. }
  28. // 处理直接进入路由非首页时,tabbarIndex 不正确的问题
  29. tabbarStore.setAutoCurIdx(path)
  30. if (LOGIN_PAGE_LIST.includes(path)) {
  31. console.log('000')
  32. return
  33. }
  34. const userStore = useUserStore()
  35. if (userStore.hasLogin) {
  36. return
  37. }
  38. console.log('拦截器中得到的 path:', path, userStore.hasLogin)
  39. if (EXCLUDE_PAGE_LIST.includes(path)) {
  40. console.log('111')
  41. uni.navigateTo({ url: path })
  42. return
  43. }
  44. console.log('222')
  45. const redirectUrl = `/pages/login/login?redirect=${encodeURIComponent(path)}`
  46. uni.navigateTo({ url: redirectUrl })
  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. }