| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- // pages/login/login.js
- const userApi = require('../../api/user');
- const userUtil = require('../../utils/user');
- Page({
- data: {
- username: '',
- password: '',
- loading: false
- },
- onLoad() {
- // 如果已登录,跳转到首页
- if (userUtil.isLogin()) {
- const userInfo = userUtil.getUserInfo();
- // 如果已登录的是管理员,清除登录信息并提示
- if (userInfo.userRole === 1) {
- userUtil.clearUserInfo();
- wx.showToast({
- title: '管理员请使用Web端登录',
- icon: 'none',
- duration: 2000
- });
- return;
- }
- // 普通用户直接跳转到首页
- wx.reLaunch({
- url: '/pages/index/index'
- });
- }
- },
- // 输入用户名
- onUsernameInput(e) {
- this.setData({
- username: e.detail.value
- });
- },
- // 输入密码
- onPasswordInput(e) {
- this.setData({
- password: e.detail.value
- });
- },
- // 登录
- async handleLogin() {
- const { username, password } = this.data;
-
- if (!username || !password) {
- wx.showToast({
- title: '请输入用户名和密码',
- icon: 'none'
- });
- return;
- }
- this.setData({ loading: true });
- try {
- const result = await userApi.userLogin(username, password);
- // result包含token和user
- // 后端已禁止管理员登录,这里只会是普通用户
- userUtil.saveUserInfo(result.user, result.token);
-
- wx.showToast({
- title: '登录成功',
- icon: 'success'
- });
- setTimeout(() => {
- wx.reLaunch({
- url: '/pages/index/index'
- });
- }, 1500);
- } catch (error) {
- wx.showToast({
- title: error || '登录失败',
- icon: 'none',
- duration: 2000
- });
- } finally {
- this.setData({ loading: false });
- }
- },
- // 跳转到注册页
- goToRegister() {
- wx.navigateTo({
- url: '/pages/register/register'
- });
- }
- });
|