vue3笔记(10-1)mock数据-mockjs

mock数据的好处,万一遇到居家办公,本地就能完成开发。
本篇基于mockjs开发。

步骤

1. 安装mockjs包

1
npm install mockjs --save

2. 修改.env.dev

1
2
3
4
5
NODE_ENV = 'development'
VUE_APP_TITLE = 'development'
VUE_APP_INTERFACE_URL="/"
VUE_APP_PROXYURL='/'
VUE_APP_MOCK = true

3. 新建mock文件夹

3.1 @/mock/api/存放***.json文件,为API文件。
3.2 @/mock/utils/存放mock相关代码。
formatOptions.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import qs from "qs";

export default function formatOptions(options) {
let { url, type, body } = options;
let params = null;
if (type === "GET" || type === "DELETE") {
let index = url.indexOf("?");
let paramsString = index > -1 ? url.slice(index + 1) : "";
if (paramsString !== "") {
params = qs.parse(paramsString);
}
} else {
params = {};
if (body instanceof FormData) {
for (let [key, value] of body.entries()) {
}
} else {
try {
params = JSON.parse(body);
} catch (e) {
params = qs.parse(body);
}
}
}
if (params !== null && Object.keys(params).length === 0) {
params = null;
}
return { url, type, params };
}

mock.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import Mock from "mockjs";
import formatOptions from "./formatOptions";

Mock._mock = Mock.mock;
Mock.mock = function (url, method, resFunc) {
if (arguments.length === 1) {
return this._mock(url);
}
if (arguments.length === 2) {
console.error(
"Function Mock.mock require three params: url, method, resFunc!!!"
);
return;
}
if (arguments.length === 3) {
let methods = ["get", "post", "put", "delete"];
if (!methods.includes(method.toLowerCase())) {
console.error(
"Function Mock.mock's second param should be get, post, put, delete!!!"
);
return;
}
if (typeof resFunc !== "function") {
console.error("Function Mock.mock's third param should be a function!!!");
return;
}
}
// 将注册的 url 转成能匹配查询字符串的正则
if (typeof url === "string") {
url = url.replace(/\//g, "\\/");
url += "(|\\?.*)$";
url = new RegExp(url);
} else if (!(url instanceof RegExp)) {
console.error(
"Function Mock.mock's first param should be a string or regexp!!!"
);
return;
}
this._mock(url, method, function (options) {
// 格式化 options 对象
options = formatOptions(options);
let res = null;
try {
res = resFunc(options);
} catch (err) {
res = err;
}
return res;
});
};
export default Mock;

3.3 @/mock/index.ts为开启mock的主要文件。

1
2
3
4
5
6
7
8
import Mock from "./utils/mock";

Mock.setup({ timeout: 2000 });
import getgenInfoJSON from "@/mock/api/getgenInfo.json";

Mock.mock("http://0.0.0.0:8080/api/v1/getgenInfo", "get", (options) => {
return getgenInfoJSON;
});

4. 在AppMain.vue中按环境引入

1
2
3
if(process.env.VUE_APP_MOCK) {
require("@/mock/index")
}

5. 开启

1
npm run dev

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!