四零语境后端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.8 KiB

1 month ago
  1. /**
  2. *
  3. *
  4. * 便使
  5. */
  6. import { useUserStore } from '@/store'
  7. import { needLoginPages as _needLoginPages, getNeedLoginPages } from '@/utils'
  8. // TODO Check
  9. const loginRoute = '/pages/login/index'
  10. const isLogined = () => {
  11. const userStore = useUserStore()
  12. return userStore.isLogined
  13. }
  14. const isDev = import.meta.env.DEV
  15. // 黑名单登录拦截器 - (适用于大部分页面不需要登录,少部分页面需要登录)
  16. const navigateToInterceptor = {
  17. // 注意,这里的url是 '/' 开头的,如 '/pages/index/index',跟 'pages.json' 里面的 path 不同
  18. invoke({ url }: { url: string }) {
  19. // console.log(url) // /pages/route-interceptor/index?name=feige&age=30
  20. const path = url.split('?')[0]
  21. let needLoginPages: string[] = []
  22. // 为了防止开发时出现BUG,这里每次都获取一下。生产环境可以移到函数外,性能更好
  23. if (isDev) {
  24. needLoginPages = getNeedLoginPages()
  25. } else {
  26. needLoginPages = _needLoginPages
  27. }
  28. const isNeedLogin = needLoginPages.includes(path)
  29. if (!isNeedLogin) {
  30. return true
  31. }
  32. const hasLogin = isLogined()
  33. if (hasLogin) {
  34. return true
  35. }
  36. const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
  37. uni.navigateTo({ url: redirectRoute })
  38. return false
  39. },
  40. }
  41. export const routeInterceptor = {
  42. install() {
  43. uni.addInterceptor('navigateTo', navigateToInterceptor)
  44. uni.addInterceptor('reLaunch', navigateToInterceptor)
  45. uni.addInterceptor('redirectTo', navigateToInterceptor)
  46. uni.addInterceptor('switchTab', navigateToInterceptor)
  47. },
  48. }