查(分页、多条件查询):
关键代码:
Mock.mock('/vue-table-list/tableLinkage/list', 'post', (option) => {// console.log("🚀 ~ file: tableLinkage.js:66 ~ Mock.mock ~ option:", option)const params = JSON.parse(option.body) // 获取查询参数const paramsKeyArr = Object.keys(params) // 获取查询参数的key值// console.log("🚀 ~ file: tableLinkage.js:47 ~ Mock.mock ~ paramsKeyArr:", paramsKeyArr)// console.log("🚀 ~ file: tableLinkage.js:46 ~ Mock.mock ~ params:", params)// console.log("🚀 ~ file: tableLinkage.js:140 ~ queryList ~ tableLinkageData:", tableLinkageData)// 例,companyCodeList 是下拉框多选出来的数组,数组内的值对应 列表的 companyCodeconst paramsMap = {'companyCodeList': 'companyCode' }// tableLinkageData 是列表数据const multipleArr = tableLinkageData.data.filter(item => {let key = 'companyCodeList'// 若多选数组长度为0,则直接返回原有列表数据if (params[key].length === 0) {return true} else {// 若不为0,则根据多选数组内的值(params[key] =》 value)与列表数据的值(item[paramsMap[key]])对比,相等则返回相应的数据(tableLinkageData.data =》item)let flag = falseparams[key].map(value => {if (value && (item[paramsMap[key]] + '') === (value + '')) {flag = true}})return flag}})// console.log("🚀 ~ file: tableLinkage.js:149 ~ multipleArr ~ multipleArr:", multipleArr)const queryList = multipleArr.filter(item => {// const queryList = tableLinkageData.data.filter(item => {let flag = trueparamsKeyArr.map(key => {if (key !== 'companyCodeList') {// 只要列表行数据内容有一个不与查询参数一致,则排除这条数据if (params[key] && item[key]?.indexOf(params[key]) === -1) {flag = false}}})return flag})// console.log("🚀 ~ file: tableLinkage.js:61 ~ queryList ~ queryList:", queryList)// 根据搜索条件得到最终的数据,并对数据进行分页const list = getSelectList(queryList, params.pageNum, params.pageSize)// console.log("🚀 ~ file: tableLinkage.js:48 ~ Mock.mock ~ list:", list)return {code: 200,msg: '操作成功',total: tableLinkageData.data.length,data: null,rows: [...list]}
})
根据搜索条件得到最终的数据,并对数据进行分页:
const list = getSelectList(queryList, params.pageNum, params.pageSize)
// 对表格数据分页
const getSelectList = (data, pageNum, pageSize) => {const start = Math.ceil(((pageNum - 1) * pageSize).toFixed(0)),end = Math.ceil((start + pageSize).toFixed(2))const list = data.slice(start >= 0 ? start : 0, end)return list
}
全部代码:
const Mock = require('mockjs')
// 对表格数据分页
const getSelectList = (data, pageNum, pageSize) => {const start = Math.ceil(((pageNum - 1) * pageSize).toFixed(0)),end = Math.ceil((start + pageSize).toFixed(2))const list = data.slice(start >= 0 ? start : 0, end)return list
}
Mock.mobile_prefix = ["134","135","136","137","138","139","150","151","152","157","158","159","130","131","132","155","156","133","153"
]
Mock.bank_prefix = ["4367","6227","6228","9559","6222","9558","6216","4563","6013","6221","6210","6014","5218","6282","3568","6226","4218","6229","4864","6029","9988"
]
Mock.numeric = "0123456789"
Mock.random = (len, list) => {if (len <= 1) {len = 1}var s = ""var n = list.lengthif (typeof list === "string") {while (len-- > 0) {s += list.charAt(Math.random() * n)}} else if (list instanceof Array) {while (len-- > 0) {s += list[Math.floor(Math.random() * n)]}}return s
}
Mock.getMobile = () => {return Mock.random(1, Mock.mobile_prefix) + Mock.random(8, Mock.numeric)
}
Mock.getBank = () => {return Mock.random(1, Mock.bank_prefix) + Mock.random(15, Mock.numeric)
}
const Random = Mock.Random
const tableLinkageData = Mock.mock({//输出数据//还可以自定义其他数据// code: 200,// msg: '操作成功',// total: 75,"data|75": [{// 'id': "@increment",'id|+1': 1,'bankAccountId': '@id()','companyCode|+1': 1,// 'companyName': `公司${'@increment(1)'}`,'accountType|1': ['1', '2'],// 'accountTypeDesc|1': ['银行帐号', '虚拟子户'],'no': '@string(3,50)', // 生成3-50位的保养合同号'subBranch': Random.cword(2,4)+'银行','cardNum': /^([1-9]{1})(\d{14}|\d{18})$/, // 随机生成银行卡卡号// 'cardNum': Mock.getBank(), // 随机生成银行卡卡号(统一19位)'phone': Mock.getMobile(), // 手机号// 'phone': /^1[358][1-9]\d{8}/,'name': `${Random.first()} ${Random.last()}`, // 人员姓名'groups': Random.integer(), // 组织编号'groupNames': `${Random.first()} ${Random.last()}`, // 组织名称// 'idCard': Random.integer(), // 身份证'desc': Random.cparagraph(),'avatar': Random.image('250x250', Random.color()),'qrCode': Random.image('720x300', Random.color(), 'bg-img'), //二维码'address': Random.city(true),'status|1': ['0', '1'],'type|1': ['0', '1'],// 'statusDesc|1': ['启用', '禁用'],'jobType|1': ['前端工程师', '后端工程师', 'UI工程师', '需求工程师'],'preview': Random.ctitle(3, 5),'email': '@email','remark': "@csentence(50)",'createdBy': "@cname()",'createdAt': "@date(yyyy-MM-dd)",'updatedBy': "@cname()",'updatedAt': "@date(yyyy-MM-dd hh:mm:ss)",}]
})Mock.mock('/vue-table-list/tableLinkage/list', 'post', (option) => {// console.log("🚀 ~ file: tableLinkage.js:66 ~ Mock.mock ~ option:", option)const params = JSON.parse(option.body) // 获取查询参数const paramsKeyArr = Object.keys(params) // 获取查询参数的key值// console.log("🚀 ~ file: tableLinkage.js:47 ~ Mock.mock ~ paramsKeyArr:", paramsKeyArr)// console.log("🚀 ~ file: tableLinkage.js:46 ~ Mock.mock ~ params:", params)// console.log("🚀 ~ file: tableLinkage.js:140 ~ queryList ~ tableLinkageData:", tableLinkageData)// 例,companyCodeList 是下拉框多选出来的数组,数组内的值对应 列表的 companyCodeconst paramsMap = {'companyCodeList': 'companyCode' }// tableLinkageData 是列表数据const multipleArr = tableLinkageData.data.filter(item => {let key = 'companyCodeList'// 若多选数组长度为0,则直接返回原有列表数据if (params[key].length === 0) {return true} else {// 若不为0,则根据多选数组内的值(params[key] =》 value)与列表数据的值(item[paramsMap[key]])对比,相等则返回相应的数据(tableLinkageData.data =》item)let flag = falseparams[key].map(value => {if (value && (item[paramsMap[key]] + '') === (value + '')) {flag = true}})return flag}})// console.log("🚀 ~ file: tableLinkage.js:149 ~ multipleArr ~ multipleArr:", multipleArr)const queryList = multipleArr.filter(item => {// const queryList = tableLinkageData.data.filter(item => {let flag = trueparamsKeyArr.map(key => {if (key !== 'companyCodeList') {// 只要列表行数据内容有一个不与查询参数一致,则排除这条数据if (params[key] && item[key]?.indexOf(params[key]) === -1) {flag = false}}})return flag})// console.log("🚀 ~ file: tableLinkage.js:61 ~ queryList ~ queryList:", queryList)// 根据搜索条件得到最终的数据,并对数据进行分页const list = getSelectList(queryList, params.pageNum, params.pageSize)// console.log("🚀 ~ file: tableLinkage.js:48 ~ Mock.mock ~ list:", list)return {code: 200,msg: '操作成功',total: tableLinkageData.data.length,data: null,rows: [...list]}
})
使用:
data() {return {// 遮罩层// loading: false,tableLoading: false,// 显示搜索条件showSearch: true,// 查询参数queryParams: {pageNum: 1,pageSize: 10,companyCodeList: [],cardNum: null,accountType: null,transactionTime: [],},}
},methods: {getList() {const res = await axios.get('/vue-table-list/tableLinkage/list', this.queryParams)}
}
模拟根据id查询对应数据 get
// 使用响应数据的函数,含有 url、type 和 body 三个属性
// 根据url 获取参数
Mock.mock(/listById/, 'get', ({ url }) => {// 获取?后面的参数const query = url.split('?')[1]// 解析参数const queryStr = new URLSearchParams(query)const id = queryStr.get('id')return {code: 0,data: list.data.find(item => item.id === Number(id))}
})
methods: {getDetailById() {const res = await axios.get('listById', { params: { id: 1 } })}
}
增加数据 post
// 如果是put | post 的请求 参数是放在了body里面
Mock.mock(/addItem/, 'post', ({ body }) => {// 获取请求体的数据const { data } = JSON.parse(body)// 对一些必填的字段做校验const dataTips = {name: '名字不能为空',sex: '性别不能为空',phone: '手机号码不能为空',account: '账号不能为空'}for (const key of Object.keys(dataTips)) {if (!data[key]) {return { code: 500, message: dataTips[key] }}}return { code: 200, data: '操作成功' }
})
使用:
// 返回 500 msg: '手机号码不能为空'
methods: {addItem () {const params = {name: 'lily',sex: '女'}const res = axios.post('/addItem', { data: params })}
}
// 返回200 ,msg: 操作成功
methods: {addItem () {const params = {name: 'lily',sex: '女',phone: '15915888888',account: 'aaa.com'}const res = axios.post('/addItem', { data: params })console.log(res, '===>addItem')}
}
根据id删除对应数据 delete
Mock.mock(/removeById/, 'delete', ({ url }) => {// 获取?后面的参数const query = url.split('?')[1]// 解析参数const queryStr = new URLSearchParams(query)const id = queryStr.get('id')const index = list.data.findIndex(item => item.id === id)list.data.splice(index, 1)return {code: 200,data: '操作成功'}
})
使用:
methods: {removeItemlById () {const res = axios.delete('/removeById', { params: { id: 1 } })}}
根据id修改对应数据 put
// 如果是put | post 的请求 参数是放在了body里面
Mock.mock(/updateById/, 'put', ({ body }) => {// 格式化body的参数const { data } = JSON.parse(body)// 找到对应的数据const target = list.data.find(item => item.id === data.id)if (!target) {return { code: 500, message: '查询有误' }}for (const key in data) {target[key] = data[key]}return { code: 0, data: target }
})
使用:
methods: {async updatetemlById () {const res = await axios.put('/updateById', { data: { id: 1, name: '我是修改的名字', role: '我是修改的role', account: '我是修改的账号' } })console.log(res, '===>updatetemlById')}}
相关文章:
前端在项目中使用mockjs模拟数据的增删改查_mockjs增删改查-CSDN博客
vue快速入门七(mock.js,js实现组件路由,总线)_mockjs vue-CSDN博客
Vue后台 - 利用 mockjs 完成数据的获取、编辑、增加、删除和分页【详细步骤篇】_vue获取数据并分页-CSDN博客 004:vue中安装使用Mock来模拟数据(详细教程)_vue模拟数据mock-CSDN博客
如何在vue中使用mockjs模拟接口的各种数据_mock模拟带参数的接口数据-CSDN博客
vue 使用 mock.js_vue mockjs-CSDN博客
使用Mockjs模拟接口实现增删改查、分页及多条件查询_vue.js_脚本之家
vue项目使用mock模拟数据并实现列表的增、删、分页、批量操作功能_vue mock如何模拟新增-CSDN博客