login.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // pages/login/login.js
  2. const userApi = require('../../api/user');
  3. const userUtil = require('../../utils/user');
  4. Page({
  5. data: {
  6. username: '',
  7. password: '',
  8. loading: false
  9. },
  10. onLoad() {
  11. // 如果已登录,跳转到首页
  12. if (userUtil.isLogin()) {
  13. const userInfo = userUtil.getUserInfo();
  14. // 如果已登录的是管理员,清除登录信息并提示
  15. if (userInfo.userRole === 1) {
  16. userUtil.clearUserInfo();
  17. wx.showToast({
  18. title: '管理员请使用Web端登录',
  19. icon: 'none',
  20. duration: 2000
  21. });
  22. return;
  23. }
  24. // 普通用户直接跳转到首页
  25. wx.reLaunch({
  26. url: '/pages/index/index'
  27. });
  28. }
  29. },
  30. // 输入用户名
  31. onUsernameInput(e) {
  32. this.setData({
  33. username: e.detail.value
  34. });
  35. },
  36. // 输入密码
  37. onPasswordInput(e) {
  38. this.setData({
  39. password: e.detail.value
  40. });
  41. },
  42. // 登录
  43. async handleLogin() {
  44. const { username, password } = this.data;
  45. if (!username || !password) {
  46. wx.showToast({
  47. title: '请输入用户名和密码',
  48. icon: 'none'
  49. });
  50. return;
  51. }
  52. this.setData({ loading: true });
  53. try {
  54. const result = await userApi.userLogin(username, password);
  55. // result包含token和user
  56. // 后端已禁止管理员登录,这里只会是普通用户
  57. userUtil.saveUserInfo(result.user, result.token);
  58. wx.showToast({
  59. title: '登录成功',
  60. icon: 'success'
  61. });
  62. setTimeout(() => {
  63. wx.reLaunch({
  64. url: '/pages/index/index'
  65. });
  66. }, 1500);
  67. } catch (error) {
  68. wx.showToast({
  69. title: error || '登录失败',
  70. icon: 'none',
  71. duration: 2000
  72. });
  73. } finally {
  74. this.setData({ loading: false });
  75. }
  76. },
  77. // 跳转到注册页
  78. goToRegister() {
  79. wx.navigateTo({
  80. url: '/pages/register/register'
  81. });
  82. }
  83. });