一、思路
1)设置mock数据
index.tsx
export * from './layout' ;
export * from './component';
export * from './user';
export * from './dashboard';
component.tsx
import Mock from 'mockjs';
const getComponentList = () => {
const data = [];
for (let i = 0; i < 20; i++) {
data.push({
title: 'ID' + i,
url: '/dashboard/details',
img: 'img/component/demo.jpg'
});
}
return data
}
function responseData() {
const data = [];
for (let i = 0; i < 10; i++) {
data.push(Mock.mock({
name: 'name' + i,
'value|1-100': 100
}));
}
return data;
}
export const component = {
"/component/list": {
data: getComponentList()
},
'/component/add/response': responseData()
}
2)检测mock配置
下发前先检测是否配置mock,如果mock数据已经做过配置 则使用mock,否则下发
// 导出配置的mock数据
import * as MOCKDATA from '@mocks/index';
import HttpClient from '../HttpClient';
// 语法检查 临时转换
const MOCKDATACACHE: any = MOCKDATA;
// 将数据拿出来
const mockData = Object.keys(MOCKDATA as any).map((key: any) => {
return MOCKDATACACHE[key];
});
/**
* 模拟mock
* @param {any} url
* @param {any} method
* @param {any} params
* @returns {Promise<any>}
*/
export default async function setMockService({
url,
method,
params
}: any) {
return new Promise((resolve, reject) => {
// 查找设置的mock值 如果找到 就使用mock数据 找不到就尝试后台获取
let mock: any;
for (let i = 0; i < mockData.length; i++) {
const item = mockData[i];
if (item[url]) {
mock = item[url];
break;
}
}
if (mock) {
setTimeout(() => {
resolve(mock);
}, 300);// 模拟300ms
} else {
// 去后台获取
return HttpClient.creatAxiosAsync({
url,
method,
params
}).then((res: any) => {
resolve(res);
});
}
})
}