前端页面开发如何使用mock数据
本际云服务器推荐网的小编小本本在前端页面开发中常常遇到后端接口没有完成的情况,这时候就可以使用mock数据来进行联调。

如何模拟CURD接口
在使用mock数据进行CURD操作时,可以与后端约定好接口路径以及入参返参的字段,避免二次修改。
首先,我们可以在安装mockjs并新建js文件,然后在文件中导入mock.js,模拟列表数据:
yarn add mockjs
const Mock = require("mockjs")
const list = []
const length = 18
for (let i = 0; i < length; i++) {
list.push(
Mock.mock({
id: '@id',
account: '@first',
name: '@name',
email: '@email',
mobile: '@phone',
sex: '@integer(0,1)',
type: "@integer(100,101)",
status: "@integer(0,1)",
})
)
}
接着模拟查询列表接口:
{
url: "/user/getPageList",
type: "post",
response: config => {
// 拿到入参
const {
name,
account,
status,
type,
pageNum,
pageSize,
} = config.body;
// 做一些查询条件的处理
const mockData = list.filter(item => {
if (name && item.name.indexOf(name) < 0) return false
if (account && item.account.toString() !== account) return false
if (status && item.status.toString() !== status) return false
if (type && item.type.toString() !== type) return false
return true
})
// 模拟分页
const pageList = mockData.slice((pageNum - 1) * pageSize, pageNum * pageSize)
// 返回数据
return {
resultCode: "1",
messageCode: null,
message: null,
data: {
list: pageList,
total: mockData.length
}
};
}
}
接着,可以模拟删除功能接口:
{
url: "/user/removeRow",
type: "post",
response: config => {
const {
id
} = config.body
// 根据id找到需要删除的元素索引
const index = list.findIndex(item => item.id === id)
// 调用splice删除
list.splice(index, 1)
return {
resultCode: "1",
messageCode: null,
message: null,
data: 'success'
}
}
}
最后,可以模拟保存及编辑接口:
{
url: "/user/saveForm",
type: "post",
response: config => {
const {
id
} = config.body
if (id) {
// 关键在于id,其他入参不多赘述,格局id找到那条数据调用splice替换
const index = list.findIndex(item => item.id === id)
list.splice(index, 1, config.body)
} else {
// 如果id不存在则在列表添加一条数据
list.unshift(
Mock.mock({
id: '@id',
...config.body
})
)
}
return {
resultCode: "1",
messageCode: null,
message: null,
data: 'success'
}
}
}
以上就是CURD接口模拟的具体方法,值得注意的是,所有接口使用module.exports导出后,在调用时就会执行mock的接口。
原创文章,作者:小编小本本,如若转载,请注明出处:https://www.benjiyun.com/yunzhujiyunwei/vps-yunwei/7264.html
