手把手讲解Vue + Element UI实现后台管理系统(四):mockjs模拟接口的使用

一、什么是mock.js

Mock.js 是一个模拟数据生成器,利用它,可以拦截ajax请求,直接模拟返回数据,这样前后端只要约定好数据格式,前端就不需要依赖后端的接口,可以直接使用模拟的数据,提升开发效率。

二、安装和使用
安装

npm install -D mockjs

搭建mock环境

首先在根目录新建mock目录,并在目录中信建一个index.js文件和modules文件夹。

index.js为mock接口处理文件
modules为mock数据

index.js代码如下:

// index.js
import Mock from "mockjs";
import {userList} from "./modules/user";

// 1. 开启/关闭[业务模块]拦截, 通过调用fnCreate方法[isOpen参数]设置.
// 2. 开启/关闭[业务模块中某个请求]拦截, 通过函数返回对象中的[isOpen属性]设置.
fnCreate(userList, true);

/**
 * 创建mock模拟数据
 * @param {*} mod 模块
 * @param {*} isOpen 是否开启?
 */
function fnCreate(mod, isOpen = true) {
  if (isOpen) {
    for (var key in mod) {
      ((res) => {
        if (res.isOpen !== false) {
          Mock.mock(new RegExp(res.url), res.type, (opts) => {
            opts["data"] = opts.body ? JSON.parse(opts.body) : null;
            delete opts.body;
            console.log("\n");
            console.log("%cmock拦截, 请求: ", "color:blue", opts);
            console.log("%cmock拦截, 响应: ", "color:blue", res.data);
            return res.data;
          });
        }
      })(mod[key]() || {});
    }
  }
}

modules下面的user.js代码:

const userList = {
  url: "/user/list",
  type: "get",
  response: () => {
    return {
      code: 20000,
      data: [
        {
          id: 1,
          username: "zhoujielun",
          password: "123456",
        },
        {
          id: 2,
          username: "guojingming",
          password: "666666",
        },
      ],
    };
  },
};

const userList1 = {
  url: "/user/list1",
  type: "get",
  response: () => {
    return {
      code: 20000,
      data: [
        {
          id: 1,
          username: "zhoujielun",
          password: "123456",
        },
        {
          id: 2,
          username: "guojingming",
          password: "666666",
        },
      ],
    };
  },
};

module.exports = [userList, userList1];
使用

需要使用的组件先引用mock/index.js

import mock from "@/mock/index.js";

然后通过封装的接口请求组件调用:

this.$http.userList().then(resp=>{
    debugger
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

longerJue

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值