vue --- > configureWebpack模拟后台数据

初识

  • 使用vue/cli搭建的项目可以在vue.config.js中,模拟一个后台(express写法)
  • vue.config.js
configureWebpack: {
    devServer: {
        // 模拟后台服务器 express写法
        before(app) {
            app.get('/api/login', function(req, res) {
                const { username, passwd } = req.query;
                console.log(username, passwd);

                if (username === 'admin' && passwd === '123456') {
                    res.json({ code: 1, token: '奇怪的栗子' });
                } else {
                    res
                        .status(401)
                        .json({ code: 0, message: '用户名或密码错误' });
                }
            });
        }
    }
}

前端请求.

  • 准备 /src/service/user.js
  • 对用户接口进行管理
import axios from 'axios';

export default {
    login(user) {
        return axios.get('/api/login', { params: user })
    }
}
  • store.js
import Vue from 'vue'
import Vuex from 'vuex'
import us from './service/user';

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        isLogin: false
    },
    mutations: {
        setLoginState(state, b) {
            state.isLogin = b;
        }
    },
    actions: {
        login({ commit }, user) {
            // 登录请求
            return us.login(user).then(res => {
                const { code, token } = res.data;
                if (code) {
                    // 登录成功
                    commit('setLoginState', true);
                    localStorage.setItem('token', token);
                }
                return code;
            })
        }
    },
    modules: {}
})

登录组件

  • login.vue
  • 在其方法里面写(vue 2.x)
 methods: {
    handleLogin(e) {
      // 组织表单的默认提交行为
      e.preventDefault();

      // 登录请求
      this.$store.dispatch('login', this.model)
        .then(code => {
          if (code) {
            // 登录成功,重定向
            const path = this.$route.query.redirect || '/';
            this.$router.push(path);
          }
        })
        .catch(error => {
          // 有错误发生或者登录失败
          const toast = this.$createToast({
            time: 2000,
            txt: error.message || error.response.data.message || '登录失败',
            type: 'error'
          });
          toast.show();
        })
    },
  }
  • 故意输入错误的

在这里插入图片描述

  • 输入正确则跳转
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值