login.vue 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <template>
  2. <view>
  3. <view class="login-background">
  4. <!-- 背景图-->
  5. <view class="login-background-img">
  6. <!-- 背景图样 -->
  7. <!-- <image class="logo" src="/static/loginBGimg.png"></image> -->
  8. <!-- icon -->
  9. <!-- <image class="logo" src="/static/loginIcon.png"></image> -->
  10. </view>
  11. <!-- 文字和按钮 -->
  12. <view class="login-text-and-buttons">
  13. <view class="login-text">
  14. </view>
  15. <button class="login-buttons" open-type="getPhoneNumber" @getphonenumber="login">获取手机号</button>
  16. </view>
  17. </view>
  18. </view>
  19. </template>
  20. <script>
  21. export default {
  22. data() {
  23. return {
  24. }
  25. },
  26. onLoad() {
  27. // 检查是否已经登录
  28. this.checkLoginStatus();
  29. },
  30. methods: {
  31. // 检查登录状态
  32. checkLoginStatus() {
  33. const token = uni.getStorageSync('token');
  34. if (token) {
  35. // 已登录,跳转到首页
  36. uni.switchTab({
  37. url: '/pages/index/index'
  38. });
  39. }
  40. },
  41. // 登录方法
  42. login(e) {
  43. console.log('[getPhoneNumber]', e);
  44. if (e.detail.errMsg === 'getPhoneNumber:ok') {
  45. // 用户同意授权
  46. console.log('用户同意授权', e.detail);
  47. // 获取code
  48. uni.login({
  49. provider: 'weixin',
  50. success: (loginRes) => {
  51. // 获取到code后,发送到后端
  52. const params = {
  53. code: loginRes.code,
  54. encryptedData: e.detail.encryptedData,
  55. iv: e.detail.iv
  56. };
  57. // 调用后端接口解密手机号
  58. uni.request({
  59. url: 'YOUR_API_URL/api/login/phone', // 替换为您的实际接口地址
  60. method: 'POST',
  61. data: params,
  62. success: (res) => {
  63. if (res.data.code === 200) {
  64. // 登录成功,保存token
  65. uni.setStorageSync('token', res.data.data.token);
  66. // 跳转到首页
  67. uni.switchTab({
  68. url: '/pages/index/index'
  69. });
  70. } else {
  71. uni.showToast({
  72. title: res.data.msg || '登录失败',
  73. icon: 'none'
  74. });
  75. }
  76. },
  77. fail: (err) => {
  78. console.error('登录请求失败', err);
  79. uni.showToast({
  80. title: '网络错误,请重试',
  81. icon: 'none'
  82. });
  83. }
  84. });
  85. },
  86. fail: (err) => {
  87. console.error('获取code失败', err);
  88. uni.showToast({
  89. title: '登录失败,请重试',
  90. icon: 'none'
  91. });
  92. }
  93. });
  94. } else {
  95. // 用户拒绝授权
  96. console.log('用户拒绝授权', e.detail);
  97. uni.showToast({
  98. title: '需要授权手机号才能使用',
  99. icon: 'none'
  100. });
  101. }
  102. }
  103. }
  104. }
  105. </script>
  106. <style>
  107. .login-buttons {
  108. margin-top: 500px;
  109. background: red;
  110. width: 249rpx;
  111. height: 57rpx;
  112. line-height: 57rpx;
  113. text-align: center;
  114. color: #fff;
  115. font-size: 28rpx;
  116. }
  117. </style>