137 lines
3.2 KiB
TypeScript
137 lines
3.2 KiB
TypeScript
|
import request from '../../utils/request';
|
||
|
|
||
|
Component({
|
||
|
data: {
|
||
|
username: '',
|
||
|
password: '',
|
||
|
isRegister: false // 控制是登录还是注册模式
|
||
|
},
|
||
|
|
||
|
methods: {
|
||
|
// 切换登录/注册模式
|
||
|
switchMode() {
|
||
|
this.setData({
|
||
|
isRegister: !this.data.isRegister
|
||
|
});
|
||
|
},
|
||
|
|
||
|
// 输入手机号
|
||
|
onPhoneInput(e: any) {
|
||
|
this.setData({
|
||
|
username: e.detail.value
|
||
|
});
|
||
|
},
|
||
|
|
||
|
// 输入密码
|
||
|
onPasswordInput(e: any) {
|
||
|
this.setData({
|
||
|
password: e.detail.value
|
||
|
});
|
||
|
},
|
||
|
|
||
|
// 登录
|
||
|
async handleLogin() {
|
||
|
console.log('开始登录:', this.data);
|
||
|
|
||
|
const { username, password } = this.data;
|
||
|
if (!username || !password) {
|
||
|
wx.showToast({
|
||
|
title: '请输入账号和密码',
|
||
|
icon: 'none'
|
||
|
});
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
try {
|
||
|
console.log('发送登录请求...');
|
||
|
const res = await request.post('/user/login', {
|
||
|
activeTab: "account",
|
||
|
username,
|
||
|
password
|
||
|
});
|
||
|
console.log('登录响应:', res);
|
||
|
|
||
|
if (res.code === 200) {
|
||
|
console.log('登录成功,保存信息...');
|
||
|
// 保存用户信息和token
|
||
|
wx.setStorageSync('userInfo', res.data);
|
||
|
wx.setStorageSync('token', res.data);
|
||
|
|
||
|
console.log('准备跳转...');
|
||
|
// 显示成功提示并跳转
|
||
|
wx.showToast({
|
||
|
title: '登录成功',
|
||
|
icon: 'success',
|
||
|
mask: true,
|
||
|
duration: 1500,
|
||
|
success: () => {
|
||
|
setTimeout(() => {
|
||
|
wx.switchTab({
|
||
|
url: '/pages/index/index',
|
||
|
success: () => {
|
||
|
console.log('跳转成功');
|
||
|
},
|
||
|
fail: (error) => {
|
||
|
console.error('跳转失败:', error);
|
||
|
}
|
||
|
});
|
||
|
}, 1500);
|
||
|
}
|
||
|
});
|
||
|
} else {
|
||
|
console.log('登录失败:', res.message);
|
||
|
wx.showToast({
|
||
|
title: res.message || '登录失败',
|
||
|
icon: 'none'
|
||
|
});
|
||
|
}
|
||
|
} catch (error) {
|
||
|
console.error('登录出错:', error);
|
||
|
wx.showToast({
|
||
|
title: '登录失败',
|
||
|
icon: 'none'
|
||
|
});
|
||
|
}
|
||
|
},
|
||
|
|
||
|
// 注册
|
||
|
async handleRegister() {
|
||
|
const { username, password } = this.data;
|
||
|
if (!username || !password) {
|
||
|
wx.showToast({
|
||
|
title: '请输入手机号和密码',
|
||
|
icon: 'none'
|
||
|
});
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
try {
|
||
|
const res = await request.post('/user/register', {
|
||
|
username,
|
||
|
password
|
||
|
});
|
||
|
|
||
|
if (res.code === 0) {
|
||
|
wx.showToast({
|
||
|
title: '注册成功',
|
||
|
icon: 'success'
|
||
|
});
|
||
|
this.setData({
|
||
|
isRegister: false
|
||
|
});
|
||
|
} else {
|
||
|
wx.showToast({
|
||
|
title: res.message || '注册失败',
|
||
|
icon: 'none'
|
||
|
});
|
||
|
}
|
||
|
} catch (error) {
|
||
|
console.error('注册失败:', error);
|
||
|
wx.showToast({
|
||
|
title: '注册失败',
|
||
|
icon: 'none'
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
});
|