main.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import Vue from 'vue'
  2. import App from './App'
  3. Vue.config.productionTip = false
  4. import uView from '@/uni_modules/uview-ui'
  5. Vue.use(uView)
  6. // uni.$u.config.unit = 'rpx'
  7. import utils from './utils/common.js'
  8. Vue.prototype.utils = utils;
  9. import {setData} from './utils/common.js'
  10. Vue.prototype.setData = setData;
  11. App.mpType = 'app'
  12. const app = new Vue({
  13. ...App
  14. })
  15. app.$mount()
  16. // 辅助函数:检查页面是否需要登录
  17. function checkNeedLogin(targetPath) {
  18. // 不需要登录的页面:首页、个人中心、登录相关页面、启动页
  19. const noLoginPages = [
  20. 'home/index',
  21. 'user/index',
  22. 'auth/login',
  23. 'auth/forgetPassword',
  24. 'auth/changePassword',
  25. 'auth/wxLogin',
  26. 'auth/setting',
  27. 'common/launch'
  28. ]
  29. // 移除路径中的斜杠和协议,只保留核心路径部分
  30. const normalizedPath = targetPath.replace(/^\/|^.*?:\/\//g, '')
  31. // 检查目标页面是否在不需要登录的列表中
  32. return !noLoginPages.some(page => normalizedPath.includes(page))
  33. }
  34. // 添加导航守卫,检查用户登录状态
  35. uni.addInterceptor('navigateTo', {
  36. invoke(e) {
  37. // 检查是否登录
  38. const userInfo = uni.getStorageSync('userInfo')
  39. // 目标页面路径
  40. const targetPath = e.url
  41. // 检查目标页面是否需要登录
  42. const needLogin = checkNeedLogin(targetPath)
  43. // 如果需要登录且未登录,则跳转到登录页面
  44. if (needLogin && !userInfo) {
  45. uni.navigateTo({
  46. url: '/pages/auth/login'
  47. })
  48. // 阻止原导航
  49. return false
  50. }
  51. return true
  52. }
  53. })
  54. // 同样拦截redirectTo
  55. uni.addInterceptor('redirectTo', {
  56. invoke(e) {
  57. const userInfo = uni.getStorageSync('userInfo')
  58. const targetPath = e.url
  59. const needLogin = checkNeedLogin(targetPath)
  60. if (needLogin && !userInfo) {
  61. uni.navigateTo({
  62. url: '/pages/auth/login'
  63. })
  64. return false
  65. }
  66. return true
  67. }
  68. })
  69. // 同样拦截reLaunch
  70. uni.addInterceptor('reLaunch', {
  71. invoke(e) {
  72. const userInfo = uni.getStorageSync('userInfo')
  73. const targetPath = e.url
  74. const needLogin = checkNeedLogin(targetPath)
  75. if (needLogin && !userInfo) {
  76. uni.navigateTo({
  77. url: '/pages/auth/login'
  78. })
  79. return false
  80. }
  81. return true
  82. }
  83. })
  84. // 同样拦截switchTab
  85. uni.addInterceptor('switchTab', {
  86. invoke(e) {
  87. const userInfo = uni.getStorageSync('userInfo')
  88. const targetPath = e.url
  89. const needLogin = checkNeedLogin(targetPath)
  90. if (needLogin && !userInfo) {
  91. uni.navigateTo({
  92. url: '/pages/auth/login'
  93. })
  94. return false
  95. }
  96. return true
  97. }
  98. })