开发者社区> 问答> 正文

vuecli3 如何配置mock.js。:报错

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

展开
收起
kun坤 2020-06-20 11:38:26 1175 0
1 条回答
写回答
取消 提交回答
  • 在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,
          };
        },
      },
    ];
    

     

    2020-06-20 11:38:35
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript函数 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载