没有按照vue-element-admin的方式设计登陆,先简单的实现一个登陆功能

登陆功能

完成功能思路如下:

  • router里配置访问后的BasicLayout路由及404
  • 用户点击登录按钮,将参数值提交到后台
  • 使用vuex实现参数提交
  • vuex中通过request(封装axios)模拟mock请求,返回token及角色(admin、guest、user)
  • 登陆成功返回到BasicLayout的页面,登陆失败返回404页面
  • 配置devServer及mock文件夹

router中配置

import Vue from "vue";
import VueRouter from "vue-router";
import NotFound from "@/views/404.vue";

/**
 * 重写路由的push方法
 */
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error => error);
};
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    component: () =>
      import(/* webpackChunkName: "layout" */ "@/layouts/BasicLayout.vue")
  },
  {
    path: "/about",
    name: "About",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue")
  },

  {
    path: "/user",
    component: { render: h => h("router-view") },
    children: [
      { path: "/user", redirect: "/user/login" },
      {
        path: "/user/login",
        name: "login",
        component: () =>
          import(/* webpackChunkName: "user" */ "@/views/user/Login.vue")
      },
      {
        path: "/user/register",
        name: "register",
        component: () =>
          import(/* webpackChunkName: "user" */ "@/views/user/Register.vue")
      }
    ]
  },
  { path: "*", name: "404", component: NotFound }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

export default router;

配置vuex中的方法和参数

编写方法
在store下新建modules文件夹,新建一个user的store文件user.js

配置user中的登陆方法

import router from "@/router";
import request from "@/utils/request";

const state = {
  userInfo: {
    name: "",
    token: "",
    password: "",
    roles: []
  }
};

const actions = {
  submitlogin({ commit }, { payload }) {
    const { username, password } = payload;
    //提交mock请求
    request({
      url: "/api/user/login",
      method: "post",
      data: { name: username, password: password }
    }).then(response => {
      if (response.data.userInfo.token != "error") {
        commit("SET_ROLES", response.data.userInfo.roles);
        commit("SET_NAME", response.data.userInfo.name);
        commit("SET_TOKEN", response.data.userInfo.token);
        router.push("/");
      } else {
        console.log(response.data.userInfo.token);
        router.push("/404");
      }
    });
  }
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.userInfo.token = token;
  },
  SET_NAME: (state, name) => {
    state.userInfo.name = name;
  },
  SET_ROLES: (state, roles) => {
    state.userInfo.roles = roles;
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};

在store中的index.js中注册user模块

import Vue from "vue";
import Vuex from "vuex";
import user from "./modules/user";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: { user }
});

封装axios

安装axios

yarn add axios

封装axios

import axios from "axios";

function request(options) {
  return axios(options)
    .then(res => {
      return res;
    })
    .catch(error => {
      const {
        response: { status, statusText }
      } = error;
      //后期修改为提示框
      console.log({ status: status, statusText: statusText });

      return Promise.reject(error);
    });
}

export default request;

配置mock

配置devServer,根据vue-cli及webpack中的API,配置代理mock

在vue.config.js中添加bodyParser

const bodyParser = require("body-parser");

配置devServer

 devServer: {
    before(app) {
      app.use(bodyParser.json()); //通过bodyParser获取req.body
    },
    proxy: {
      "/api": {
        target: "http://localhost:63000",
        bypass: function(req, res) {
          if (req.headers.accept.indexOf("html") !== -1) {
            console.log("Skipping proxy for browser request.");
            return "/index.html";
          } else if (process.env.MOCK !== "none") {
            const name = req.path
              .split("/api/")[1]
              .split("/")
              .join("_");
            const mock = require(`./mock/${name}`);
            const result = mock(req);
            //删除缓存.否是数据修改后不会变
            delete require.cache[require.resolve(`./mock/${name}`)];
            return res.send(result);
          }
        }
      }
    }
  },

Mock数据

在src同级目录建立mock文件夹,按照devServer中的规则建立Mock数据。测试中登陆建立的文件为user_login.js

function login(req) {
  const method = req.method;
  const { name, password } = req.body;
  let { token, roles } = "";
  let res = null;
  const userMap = new Map();
  userMap.set("admin", {
    password: "111111",
    token: "AAAAAA",
    roles: ["admin"]
  });
  userMap.set("user", {
    password: "222222",
    token: "BBBBBB",
    roles: ["user"]
  });
  userMap.set("guest", {
    password: "333333",
    token: "CCCCCC",
    roles: ["guest"]
  });

  switch (method) {
    case "POST":
      if (userMap.get(name) && userMap.get(name).password == password) {
        token = userMap.get(name).token;
        roles = userMap.get(name).roles;
      } else {
        token = "error";
      }
      res = {
        message: "HTTP OK",
        userInfo: { token: token, roles: roles, name: name }
      };
      break;

    default:
      res = null;
  }
  return res;
}

module.exports = login;

参数拦截

开始配置的时候devServer无法拦截POST请求的参数,查找文档后修改如下(完整内容见上"配置devServer")

在vue.config.js中添加bodyParser

const bodyParser = require("body-parser");

devServer中添加before的拦截

    before(app) {
      app.use(bodyParser.json()); //通过bodyParser获取req.body
    },
posted on 2020-03-04 17:02  学业未成  阅读(3433)  评论(0编辑  收藏  举报