App.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <script>
  2. export default {
  3. onLaunch: function() {
  4. console.log('App Launch')
  5. // 检查登录状态
  6. const token = uni.getStorageSync('token')
  7. if (token) {
  8. this.$store.commit('setToken', token)
  9. } else {
  10. // 无token时尝试自动登录
  11. this.tryAutoLogin()
  12. }
  13. },
  14. onShow: function() {
  15. console.log('App Show')
  16. },
  17. onHide: function() {
  18. console.log('App Hide')
  19. },
  20. methods: {
  21. async tryAutoLogin() {
  22. try {
  23. // 1. 先尝试用缓存的openid自动登录
  24. const cachedOpenid = uni.getStorageSync('openid')
  25. if (cachedOpenid) {
  26. const res = await this.request('/api/auth/auto-login', 'POST', { openid: cachedOpenid })
  27. if (res && res.data) {
  28. this.saveLoginInfo(res.data)
  29. console.log('openid自动登录成功')
  30. return
  31. }
  32. }
  33. // 2. openid自动登录失败,不自动调用uni.login(避免DevTools环境超时阻塞渲染层)
  34. // 用户会看到登录页,手动选择登录方式
  35. } catch (e) {
  36. console.log('自动登录失败,需要手动登录', e)
  37. }
  38. },
  39. saveLoginInfo(data) {
  40. uni.setStorageSync('token', data.token)
  41. uni.setStorageSync('userId', data.userId)
  42. uni.setStorageSync('role', data.role)
  43. uni.setStorageSync('familyId', data.familyId)
  44. // 自动登录后重置到真实登录角色,避免残留切换状态
  45. uni.setStorageSync('currentRole', data.role)
  46. uni.setStorageSync('isSwitchedChild', false)
  47. uni.setStorageSync('isSwitchedTeacher', false)
  48. if (data.openid) {
  49. uni.setStorageSync('openid', data.openid)
  50. }
  51. uni.setStorageSync('userInfo', {
  52. nickname: data.nickname,
  53. userId: data.userId
  54. })
  55. this.$store.commit('setToken', data.token)
  56. },
  57. request(url, method, data) {
  58. return new Promise((resolve, reject) => {
  59. uni.request({
  60. url: 'http://localhost:8080' + url,
  61. method: method,
  62. data: data,
  63. timeout: 10000,
  64. header: { 'Content-Type': 'application/json' },
  65. success: (res) => {
  66. if (res.data.code === 200) {
  67. resolve(res.data)
  68. } else {
  69. reject(res.data)
  70. }
  71. },
  72. fail: reject
  73. })
  74. })
  75. }
  76. }
  77. }
  78. </script>
  79. <style>
  80. @import url('./common/uni.css');
  81. page {
  82. background-color: #f5f5f5;
  83. }
  84. .container {
  85. padding: 20rpx;
  86. }
  87. .btn-primary {
  88. background-color: #FF6B6B;
  89. color: #fff;
  90. border-radius: 20rpx;
  91. padding: 20rpx 40rpx;
  92. text-align: center;
  93. font-size: 28rpx;
  94. }
  95. .btn-primary:active {
  96. opacity: 0.8;
  97. }
  98. </style>