vuecli3 如何配置mock.js,只需要开发环境使用mock.js 打包生产环境的包不需要用mock。js
在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,
};
},
},
];
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。