routeInterceptor.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * 路由登录拦截器(黑名单模式)
  3. * 适用:大部分页面可访问,少数页面需要登录
  4. */
  5. import { userToken } from "@/composables/config";
  6. import {
  7. needLoginPages as _needLoginPages,
  8. getNeedLoginPages,
  9. } from '@/utils/needLoginPages.js'
  10. // 登录页
  11. const LOGIN_ROUTE = '/pages/login/index'
  12. // 是否开发环境
  13. const isDev = process.env.NODE_ENV === 'development'
  14. // 拦截器主体
  15. const routeGuard = {
  16. invoke({ url }) {
  17. // 1️⃣ 解析纯路径(去掉 query)
  18. const path = url.split('?')[0]
  19. console.log(path, 222212112);
  20. // 2️⃣ 获取需要登录的页面列表
  21. const needLoginPages = isDev
  22. ? getNeedLoginPages()
  23. : _needLoginPages
  24. // 3️⃣ 是否命中黑名单
  25. const needLogin = needLoginPages.includes(path)
  26. // 4️⃣ 是否已登录
  27. const hasToken = userToken.value
  28. // 5️⃣ 放行条件
  29. if (!needLogin || hasToken) {
  30. return true
  31. }
  32. // 6️⃣ 未登录 → 跳登录页
  33. uni.navigateTo({
  34. url: LOGIN_ROUTE,
  35. })
  36. // ⚠️ 必须 return false
  37. return false
  38. },
  39. }
  40. // 对外安装方法
  41. export const routeInterceptor = {
  42. install() {
  43. uni.addInterceptor('navigateTo', routeGuard)
  44. uni.addInterceptor('redirectTo', routeGuard)
  45. uni.addInterceptor('reLaunch', routeGuard)
  46. uni.addInterceptor('switchTab', routeGuard)
  47. },
  48. }