router.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import type { App } from 'vue'
  2. import { pages, subPackages } from '@/pages.json'
  3. import { useUserStore } from '@/stores/modules/userStore'
  4. // 处理分包路由
  5. const subPages = []
  6. subPackages.forEach((item) => {
  7. if (item.pages && Array.isArray(item.pages)) {
  8. item.pages.forEach((p) => {
  9. subPages.push({
  10. actions: p.actions,
  11. path: `${item.root}/${p.path}`,
  12. })
  13. })
  14. }
  15. })
  16. // 需要拦截的页面
  17. const loginBlacklist = new Set(
  18. [...pages, ...subPages]
  19. .filter((p) => p.actions && p.actions.includes('login'))
  20. .map((p) => `/${p.path}`)
  21. )
  22. // console.log('loginBlacklist', loginBlacklist)
  23. const interceptor = {
  24. invoke({ url }) {
  25. const userStore = useUserStore()
  26. const token = userStore.token
  27. const path = url.split('?')[0]
  28. const isNeedLogin = loginBlacklist.has(path)
  29. // 不需要登录权限的,直接跳转
  30. if (!isNeedLogin) {
  31. return true
  32. }
  33. // 已经登录的,直接跳转
  34. if (token) {
  35. return true
  36. }
  37. // 访问的是需要登录权限才能查看的页面,先跳转到提示页面提醒用户
  38. const redirectRoute = `/pages-sub/auth/index?redirect=${encodeURIComponent(url)}`
  39. uni.navigateTo({ url: redirectRoute })
  40. return false
  41. },
  42. }
  43. export function setupRouterInterceptor(app: App) {
  44. app.use({
  45. install() {
  46. uni.addInterceptor('navigateTo', interceptor)
  47. uni.addInterceptor('reLaunch', interceptor)
  48. uni.addInterceptor('redirectTo', interceptor)
  49. },
  50. })
  51. }