routeInterceptor.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. // 2️⃣ 获取需要登录的页面列表
  20. const needLoginPages = isDev
  21. ? getNeedLoginPages()
  22. : _needLoginPages
  23. // 3️⃣ 是否命中黑名单
  24. const needLogin = needLoginPages.includes(path)
  25. // 4️⃣ 是否已登录
  26. const hasToken = userToken.value
  27. // 5️⃣ 放行条件
  28. if (!needLogin || hasToken) {
  29. return true
  30. }
  31. // 6️⃣ 未登录 → 跳登录页
  32. uni.navigateTo({
  33. url: LOGIN_ROUTE,
  34. })
  35. // ⚠️ 必须 return false
  36. return false
  37. },
  38. }
  39. // 对外安装方法
  40. export const routeInterceptor = {
  41. install() {
  42. uni.addInterceptor('navigateTo', routeGuard)
  43. uni.addInterceptor('redirectTo', routeGuard)
  44. uni.addInterceptor('reLaunch', routeGuard)
  45. uni.addInterceptor('switchTab', routeGuard)
  46. },
  47. }