vuecli3 如何配置mock.js。

bizvane_赵伟 发布于 2019/02/20 09:53
阅读 1K+
收藏 0

vuecli3 如何配置mock.js,只需要开发环境使用mock.js  打包生产环境的包不需要用mock。js

加载中
0
KevinGH
KevinGH

在main.js里面写引入逻辑就好了,下面是我的做法,希望对你有用。

// ... 
if (NODE_ENV === "development") {
  require("@/mock");
}
// ...

@/mock/index.js

/**
 * 目录结构
 * mock
 *  |_index.js
 *  |_client.js
 *  |_project.js
 *  |...
 *
 */
import Mock from "mockjs";
import { isNull } from "@/utils/tools";
const context = require.context("./", false, /\.js$/);

const generatorMock = option => {
  const { rurl, rtype, template } = option;
  if (isUrlNotNull(rurl) && !isNull(rtype)) {
    Mock.mock(rurl, rtype, template);
  } else if (isUrlNotNull(rurl)) {
    Mock.mock(rurl, template);
  } else {
    Mock.mock(template);
  }
};

const isUrlNotNull = url => {
  return !isNull(url) || (_.isRegExp(url) && url !== null);
};

/**
 * http://mockjs.com/examples.html
 *
 * Mock.mock(rurl?, rtype?, template|function(options))
 * {
 *  rurl: regex|string  需要拦截的URL
 *  rtype:string  拦截的请求类型,GET、POST、PUT、DELETE
 *  template: object|string|function  数据模版|生成响应数据的函数
 *    object  {'data|1-10':[{}]}
 *    string  '@EMAIL'
 *    function  ({url, type, body}) => {}
 * }
 */
context
  .keys()
  .filter(item => item !== "./index.js" && !_.startsWith(item, "./_"))
  .forEach(key => {
    const namespace = key.substring(key.lastIndexOf("/") + 1, key.lastIndexOf("."));
    const options = context(key).default;
    if (_.isArray(options)) {
      _.forEach(options, option => generatorMock(option));
    } else if (_.isPlainObject(options)) {
      generatorMock(options);
    }
  });

Mock.setup({
  timeout: "600-2000",
});

export default Mock;

一个例子:client.js

// 客户
import Mock, { Random } from "mockjs";

import { param2Obj } from "@/utils/tools";

const List = [];
const count = 100;

for (let i = 0; i < count; i++) {
  List.push(
    Mock.mock({
      id: Random.guid(),
      customer_name: Random.name(),
      contact_name: Random.name(),
      position: Random.pick(["经理", "顾问", "普通"]),
      phone: /138\d{8}/,
      email: Random.email(),
    })
  );
}

export default [
  {
    rurl: "/mock/clients",
    template: config => {
      const { page = 1, limit = 20, sort } = param2Obj(config.url);

      const pageList = List.filter((item, index) => index < limit * page && index >= limit * (page - 1));
      return {
        code: 0,
        data: {
          current: page,
          records: pageList,
          total: List.length,
          size: limit,
        },
      };
    },
  },
  {
    rurl: /\/mock\/clients\/[^\s]*/,
    template: ({ url }) => {
      const reg = /\/mock\/clients\/([^\s]*)/;
      const group = url.match(reg);
      const uuid = _.last(group);
      const data = _.find(List, { id: uuid });
      return {
        ...data,
      };
    },
  },
];

 

OSCHINA
登录后可查看更多优质内容
返回顶部
顶部
返回顶部
顶部