1. 安装依赖:npm i mocker-api mockjs -D
2. 在development模式对应的webpack配置下添加:
before(app, server) {
// console.log('MOCK', process.env)
if(process.env.MOCK) {
// mocker-api
apiMocker(app, path.resolve(__dirname, '../mock'))
}
}
3. 添加对应的mock数据接口:
// mock/index.js
const invitation = require('./invitation')
module.exports = {
...invitation
}
// mock/invitation/index.js
const Mock = require('mockjs')
const Random = Mock.Random
var data = Mock.mock({
'list|25': [
{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|+1': 1,
parentNickName: '前端人人@id',
nickName: '前端人人@id',
inviteAvatar: '', // Random.dataImage('60x60'),
avatar: '', // Random.dataImage('60x60'),
inviteTime: new Date().getTime(),
validStatus: Random.pick([1, 2, 3, 4])
}
]
})
module.exports = {
'GET /api/inviteInfo/selflist': (req, resp) => {
// console.log('data', data)
const { page: pPage } = req.query;
// let page = 0;
const page = parseInt(pPage || '1')
let pageSize = 15;
let startIdx = (page - 1) * pageSize;
let endIdx = page * pageSize;
return resp.json({
code: 200,
data: data.list.slice(startIdx, endIdx),
message: '查询成功',
pageCount: Math.ceil(data.list.length / pageSize),
currentPage: page,
})
},
//...
}
4. package.json 文件添加运行脚本:
"start:mock": "cross-env MOCK=true npm run start",
注:如果windows环境下MOCK=true设置无效,请安装 cross-env 依赖。
如果此文章对你有帮助,请点个赞再走哦!