自由屋推书网—热门的小说推荐平台!

你的位置: 首页 > 网站技巧

Vue+Mockjs模拟curd接口请求的示例详解

2022-07-12 10:02:33

在前后端分离的项目中常常会遇到当前端页面开发完成,但是后端接口还没好,暂不支持联调的情况下,一般我们会用到mock数据,这边简单说一下最常见且经常会遇到的curd接口模拟,注:这边可以和后端先约定好接口路径以及入参返参的字段,避免二次修改。

1.安装依赖,新建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)",
})
)
}

2.查询列表接口模拟

 {
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
}
};
}
},

3.删除功能接口模拟

 {
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'
}
}
},

4.保存及编辑接口模拟

{
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接口模拟,具体mock-server.js的配置可去网上查阅
所有接口使用module.exports导出后,在调用时就会执行mock的接口

编辑推荐

热门小说