-
安装 mockjs :npm i mockjs --save-dev;
-
config 文件中添加变量设置是否使用mock:
src/config/config.development.js
mockable: true,
- 添加mock入口
import mock from 'appRoot/mock';
- 封装的myFetch处理
if (res && res.ok && res.statusCode === 200) {
const text = res.body || JSON.parse(res.text);
promise = Object.assign({}, text);
return promise;
}
- mock 书写示例
src/mock/index.js
import { config, } from 'appRoot/utils';
const all = config.mockable ? require('./all'): null;
src/mock/all.js
// 将所有的mock文件引入
import tmp from './tmp';
// 在这里可以做一些通用的配置
import Mock from 'mockjs'
Mock.XHR.prototype.__send = Mock.XHR.prototype.send
Mock.XHR.prototype.send = function () {
if (this.custom.xhr)
this.custom.xhr.withCredentials = this.withCredentials || false
this.__send.apply(this, arguments)
}
// 设置所有ajax请求的超时时间,模拟网络传输耗时
Mock.setup({
timeout: 0-300
})
以后在类似tmp.js 文件中添加mock返回;
src/mock/tmp.js
import Mock from 'mockjs'
import { config, } from 'appRoot/utils';
Mock.mock(`${config.rootApi}/tmp`, "get", function(){
let data = Mock.mock({
"code": 0,
"data": {
"fullName": "@CNAME", // 随机生成中文人名
"userId": 1000234234001,
"username": "zhangsan"
},
"msg": "success"
});
return data;
});
- example:
http://mockjs.com/examples.html
网友评论