fastbee/yack-mini/miniprogram/pages/login/login.js
2026-09-05 13:39:38 +08:00

149 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 登录页面
*/
const request = require('../../utils/request.js');
const storage = require('../../utils/storage.js');
const app = getApp();
Page({
data: {
username: '',
password: '',
captchaCode: '',
captchaUuid: '',
captchaImg: '',
captchaEnabled: false,
loading: false,
},
onLoad() {
// 检查是否已登录
if (app.isLoggedIn()) {
this._goToIndex();
return;
}
// 获取验证码配置
this._checkCaptcha();
},
/**
* 检查验证码是否启用
*/
async _checkCaptcha() {
try {
const res = await request.captchaImage();
if (res.img) {
this.setData({
captchaEnabled: true,
captchaImg: 'data:image/png;base64,' + res.img,
captchaUuid: res.uuid,
});
}
} catch (err) {
console.log('[Login] 验证码获取失败,可能未启用');
}
},
/**
* 刷新验证码
*/
refreshCaptcha() {
this._checkCaptcha();
},
/**
* 用户名输入
*/
onUsernameInput(e) {
this.setData({ username: e.detail.value });
},
/**
* 密码输入
*/
onPasswordInput(e) {
this.setData({ password: e.detail.value });
},
/**
* 验证码输入
*/
onCaptchaInput(e) {
this.setData({ captchaCode: e.detail.value });
},
/**
* 登录
*/
async handleLogin() {
const { username, password, captchaCode, captchaUuid, captchaEnabled } = this.data;
// 验证输入
if (!username) {
wx.showToast({ title: '请输入用户名', icon: 'none' });
return;
}
if (!password) {
wx.showToast({ title: '请输入密码', icon: 'none' });
return;
}
if (captchaEnabled && !captchaCode) {
wx.showToast({ title: '请输入验证码', icon: 'none' });
return;
}
this.setData({ loading: true });
try {
// 登录请求
const loginRes = await request.login(username, password, captchaCode, captchaUuid);
const token = loginRes.token;
// 先保存 token(重要:后续请求需要认证)
storage.setToken(token);
// 获取用户信息
const infoRes = await request.getInfo();
const user = infoRes.user;
// 保存用户信息
app.setLoginInfo({
token: token,
userId: user.userId,
userName: user.userName,
phonenumber: user.phonenumber,
avatar: user.avatar,
});
wx.showToast({ title: '登录成功', icon: 'success' });
// 跳转首页
setTimeout(() => {
this._goToIndex();
}, 500);
} catch (err) {
console.error('[Login] 登录失败:', err);
wx.showToast({
title: err.message || '登录失败',
icon: 'none',
});
// 刷新验证码
if (this.data.captchaEnabled) {
this._checkCaptcha();
}
} finally {
this.setData({ loading: false });
}
},
/**
* 跳转首页
*/
_goToIndex() {
wx.reLaunch({
url: '/pages/index/index',
});
},
});