main.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. 'pages_user/userAgreement',
  29. 'pages_user/privacyPolicy'
  30. ]
  31. // 移除路径中的斜杠和协议,只保留核心路径部分
  32. const normalizedPath = targetPath.replace(/^\/|^.*?:\/\//g, '')
  33. // 检查目标页面是否在不需要登录的列表中
  34. return !noLoginPages.some(page => normalizedPath.includes(page))
  35. }
  36. // 添加导航守卫,检查用户登录状态
  37. uni.addInterceptor('navigateTo', {
  38. invoke(e) {
  39. // 检查是否登录
  40. const userInfo = uni.getStorageSync('userInfo')
  41. // 目标页面路径
  42. const targetPath = e.url
  43. // 检查目标页面是否需要登录
  44. const needLogin = checkNeedLogin(targetPath)
  45. // 如果需要登录且未登录,则跳转到登录页面
  46. if (needLogin && !userInfo) {
  47. uni.navigateTo({
  48. url: '/pages/auth/login'
  49. })
  50. // 阻止原导航
  51. return false
  52. }
  53. return true
  54. }
  55. })
  56. // 同样拦截redirectTo
  57. uni.addInterceptor('redirectTo', {
  58. invoke(e) {
  59. const userInfo = uni.getStorageSync('userInfo')
  60. const targetPath = e.url
  61. const needLogin = checkNeedLogin(targetPath)
  62. if (needLogin && !userInfo) {
  63. uni.navigateTo({
  64. url: '/pages/auth/login'
  65. })
  66. return false
  67. }
  68. return true
  69. }
  70. })
  71. // 同样拦截reLaunch
  72. uni.addInterceptor('reLaunch', {
  73. invoke(e) {
  74. const userInfo = uni.getStorageSync('userInfo')
  75. const targetPath = e.url
  76. const needLogin = checkNeedLogin(targetPath)
  77. if (needLogin && !userInfo) {
  78. uni.navigateTo({
  79. url: '/pages/auth/login'
  80. })
  81. return false
  82. }
  83. return true
  84. }
  85. })
  86. // 同样拦截switchTab
  87. uni.addInterceptor('switchTab', {
  88. invoke(e) {
  89. const userInfo = uni.getStorageSync('userInfo')
  90. const targetPath = e.url
  91. const needLogin = checkNeedLogin(targetPath)
  92. if (needLogin && !userInfo) {
  93. uni.navigateTo({
  94. url: '/pages/auth/login'
  95. })
  96. return false
  97. }
  98. return true
  99. }
  100. })