axios + mock-axios-adapter实现mock数据
一套简单通用的mock数据结构文件。
特点
- 添加mock接口数据,清晰明了
- 文件目录清晰
- 启用mock功能,简单方便
文件结构
文件模板
- 总入口index.js
//mock/index.js
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import mockPlanAPIs from './plan.js';
// All requests using this instance will have a 2 seconds delay:
const mock = new MockAdapter(axios, {delayResponse: 2000});
const responses = {
...mockPlanAPIs,
};
mock.onAny().reply(({url, method = 'get', data, params}) => {
const _data = method.toUpperCase() === 'GET' ? params : data;
console.log(`url==${url};method==${method};data==`, _data);
const oneResponse = responses[`${method.toUpperCase()} ${url}`]
if (oneResponse) {
if (Object.prototype.toString.call(oneResponse) === '[object Function]') {
return [200, oneResponse(_data)];
}
return [200, oneResponse];
}
// Unexpected request, error out
return [500, {}];
});
复制代码
- 子模块 plan.js
// mock/plan.js
import Mock from 'mockjs'
export default {
// 直接写mock数据
'GET /ad/campaign/type/list': {
'code': 0,
'message': '',
'result': [
{'name': '未知33', 'id': 1},
{'name': '应用下载', 'id': 2},
{'name': '非应用下载', 'id': 3}
]
},
// 用一个函数mock数据
'GET /ad/campaign/list': params => {
const { pg = 10, pn = 1 } = params
const data = Mock.mock({
'code': 0,
'message': '',
result: {
'list': () => {
let arr = [];
for(let i = 0; i < pg; i++) {
const obj = Mock.mock({
'_id|': i + (pn - 1) * pg + 1,
title: '@ctitle',
'images|1-4':[{
cdnUri:'@image(750x500)'
}],
body: '@cparagraph',
'createdAt': '@date',
'author': {
'_id': '@natural(1000, 9999)',
'name': '@cname'
},
'address': '@county(true)'
});
arr.push(obj);
}
return arr;
}
}
});
return data
},
// 用Mock直接mock数据
'GET /ad/content/list': Mock.mock({
'code': 0,
'message': '',
'result': {
'total': 1, // 总记录数
'size': 1, // 当前页记录数
'current': 1, // 当前第几页
'records': () => {
let arr = [];
for (let i = 0; i < 10; i++) {
const obj = Mock.mock({
'_id|': i + (5 - 1) * 10 + 1,
title: '@ctitle',
'images|1-4': [{
cdnUri: '@image(750x500)'
}],
body: '@cparagraph',
'createdAt': '@date',
'author': {
'_id': '@natural(1000, 9999)',
'name': '@cname'
},
'address': '@county(true)'
});
arr.push(obj);
}
return arr;
}
}
}),
// 删除广告 by ids accountid
'POST /ad/plan/delete': {
code: 0
}
};
复制代码
- 开启mock data
// main.js
import './mock';
复制代码