App.vue 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. <script>
  2. import config from '@/config.js'
  3. import Vue from 'vue'
  4. import { checkUserFamily, verifyToken } from './utils/api.js'
  5. Vue.prototype.$config = config
  6. export default {
  7. onLaunch: function(options) {
  8. console.log('App Launch', options)
  9. // 冷启动:跳转到 splash 页展示过渡动画,2秒后自动进入首页
  10. if (options.scene !== 1047 && options.scene !== 1048 && options.scene !== 1049) {
  11. uni.setStorageSync('_isFirstLaunch', '1')
  12. uni.redirectTo({ url: '/pages/splash/index' })
  13. return
  14. }
  15. // 处理小程序码场景值(从 wxacode 扫码进入,跳过 splash)
  16. this.handleScene(options)
  17. // TabBar 始终显示 5 个底签,不因登录状态隐藏
  18. const token = uni.getStorageSync('token')
  19. if (token) {
  20. this.$store.commit('setToken', token)
  21. // 启动时校验 token 是否仍有效:过期则清理本地登录态并引导重新登录
  22. this.verifyStoredToken()
  23. // 冷启动恢复 familyId(登录时已持久化,hasFamily getter 依赖)
  24. var storedFamilyId = uni.getStorageSync('familyId')
  25. if (storedFamilyId) {
  26. this.$store.commit('setFamilyId', storedFamilyId)
  27. } else {
  28. // 历史用户(8ddc5b55 后未重新登录):本地无 familyId,从接口恢复
  29. this.restoreFamilyIdFromApi()
  30. }
  31. } else {
  32. // 无token时尝试自动登录
  33. this.tryAutoLogin()
  34. }
  35. },
  36. onShow: function(options) {
  37. console.log('App Show', options)
  38. // 每次 app 展示时也检查场景值(小程序码可能从冷启动后的 onShow 传入)
  39. this.handleScene(options)
  40. // 同步 storage → Vuex(防止 reLaunch/navigateTo 后 Vuex 未更新的问题)
  41. var token = uni.getStorageSync('token')
  42. if (token && token !== this.$store.state.token) {
  43. this.$store.commit('setToken', token)
  44. this.$store.commit('setFamilyId', uni.getStorageSync('familyId'))
  45. }
  46. },
  47. onHide: function() {
  48. console.log('App Hide')
  49. },
  50. methods: {
  51. // 校验本地 token 是否有效(开发环境跳过,避免无后端时误报)
  52. verifyStoredToken() {
  53. try {
  54. var envInfo = uni.getAccountInfoSync()
  55. if (envInfo && envInfo.miniProgram && envInfo.miniProgram.envVersion === 'develop') {
  56. return
  57. }
  58. } catch (e) { /* 非小程序环境 */ }
  59. var self = this
  60. verifyToken().then(function() {
  61. // token 有效,无需处理
  62. }).catch(function(e) {
  63. // 401 已由 request 封装触发 _clearAuthAndRedirect(清理 + 跳登录);
  64. // 其它错误(如网络失败)静默忽略,不打扰用户
  65. console.log('[App] token 校验未通过:', e && e.code)
  66. })
  67. },
  68. // 从接口恢复 familyId(历史用户冷启动,本地无 familyId 缓存)
  69. restoreFamilyIdFromApi() {
  70. var self = this
  71. checkUserFamily().then(function(res) {
  72. if (res && res.data && res.data.inFamily && res.data.familyId) {
  73. self.$store.commit('setFamilyId', res.data.familyId)
  74. console.log('[App] familyId 已从接口恢复:', res.data.familyId)
  75. }
  76. }).catch(function(e) {
  77. console.log('[App] familyId 接口恢复失败(页面按无家庭态渲染)', e)
  78. })
  79. },
  80. async tryAutoLogin() {
  81. // 开发环境下跳过自动登录,避免无后端时 10s 超时阻塞
  82. try {
  83. var envInfo = uni.getAccountInfoSync()
  84. if (envInfo && envInfo.miniProgram && envInfo.miniProgram.envVersion === 'develop') {
  85. return
  86. }
  87. } catch (e) { /* 非小程序环境 */ }
  88. try {
  89. // 1. 先尝试用缓存的openid自动登录
  90. const cachedOpenid = uni.getStorageSync('openid')
  91. if (cachedOpenid) {
  92. const res = await this.request('/api/auth/auto-login', 'POST', { openid: cachedOpenid })
  93. if (res && res.data) {
  94. this.saveLoginInfo(res.data)
  95. console.log('openid自动登录成功')
  96. // 刷新页面到登录态
  97. uni.switchTab({ url: '/pages/index-home/index' })
  98. return
  99. }
  100. }
  101. // 2. openid自动登录失败,不自动调用uni.login(避免DevTools环境超时阻塞渲染层)
  102. // 用户会看到登录页,手动选择登录方式
  103. } catch (e) {
  104. console.log('自动登录失败,需要手动登录', e)
  105. }
  106. },
  107. saveLoginInfo(data) {
  108. uni.setStorageSync('token', data.token)
  109. uni.setStorageSync('userId', data.userId)
  110. uni.setStorageSync('role', data.role)
  111. // 自动登录后重置到真实登录角色,避免残留切换状态
  112. uni.setStorageSync('currentRole', data.role)
  113. uni.setStorageSync('isSwitchedChild', false)
  114. uni.setStorageSync('isSwitchedTeacher', false)
  115. if (data.openid) {
  116. uni.setStorageSync('openid', data.openid)
  117. }
  118. // familyId 必须持久化:家庭在注册时已由后端创建,缺失会导致页面误判无家庭而重复创建
  119. uni.setStorageSync('userInfo', {
  120. nickname: data.nickname,
  121. userId: data.userId,
  122. familyId: data.familyId
  123. })
  124. this.$store.commit('setToken', data.token)
  125. // 同步 familyId 到 store(hasFamily getter 依赖;auto-login 路径)
  126. this.$store.commit('setFamilyId', data.familyId)
  127. },
  128. request(url, method, data) {
  129. return new Promise((resolve, reject) => {
  130. uni.request({
  131. url: config.api(url),
  132. method: method,
  133. data: data,
  134. timeout: 10000,
  135. header: { 'Content-Type': 'application/json' },
  136. success: (res) => {
  137. if (res.data.code === 200) {
  138. resolve(res.data)
  139. } else {
  140. reject(res.data)
  141. }
  142. },
  143. fail: reject
  144. })
  145. })
  146. },
  147. // 处理小程序码场景值,跳转到邀请页
  148. handleScene(options) {
  149. if (!options || !options.query) return
  150. var scene = options.query.scene
  151. if (!scene) return
  152. var sceneDecoded = decodeURIComponent(scene)
  153. if (sceneDecoded.indexOf('invite=') === 0) {
  154. var token = sceneDecoded.substring(7)
  155. uni.navigateTo({
  156. url: '/pages/invite/join?token=' + token
  157. })
  158. } else if (sceneDecoded.indexOf('ref=') === 0) {
  159. var refCode = sceneDecoded.substring(4)
  160. if (!refCode) {
  161. console.warn('推广码场景缺少 refCode', sceneDecoded)
  162. return
  163. }
  164. uni.navigateTo({
  165. url: '/pages/invite/join?refCode=' + encodeURIComponent(refCode)
  166. })
  167. }
  168. }
  169. }
  170. }
  171. </script>
  172. <style>
  173. @import url('./common/uni.css');
  174. page {
  175. background-color: var(--bg, #F5F9FC);
  176. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI',
  177. 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei',
  178. 'Helvetica Neue', Helvetica, Arial, sans-serif;
  179. color: var(--text, #1E293B);
  180. font-size: 28rpx;
  181. line-height: 1.6;
  182. -webkit-font-smoothing: antialiased;
  183. }
  184. /* 页面容器 */
  185. .page {
  186. padding: 0 32rpx 32rpx;
  187. min-height: 100vh;
  188. }
  189. .page--no-padding {
  190. padding: 0;
  191. }
  192. /* 分段标题 */
  193. .section-header {
  194. font-weight: 700;
  195. font-size: 32rpx;
  196. margin: 32rpx 0 16rpx;
  197. color: var(--text, #1E293B);
  198. display: flex;
  199. align-items: center;
  200. justify-content: space-between;
  201. border-left: 8rpx solid #F08A7A;
  202. padding-left: 20rpx;
  203. }
  204. .section-header__more {
  205. font-size: 24rpx;
  206. color: var(--muted, #94A3B8);
  207. font-weight: 400;
  208. }
  209. /* 安全区底部 */
  210. .safe-area-bottom {
  211. padding-bottom: calc(constant(safe-area-inset-bottom) + 20rpx);
  212. padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  213. }
  214. </style>