本文主要是介绍使用Mockjs模拟(假数据)接口(axios),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、什么是MockJs
Mock.js官网
Mock.wiki.git
mock测试就是在测试过程中,对于某些不容易构造或者不容易获取的对象,用一个虚拟的对象来创建以便测试的测试方法。
二、安装mockjs
npm install mockjs
三、 MockJs使用
简单使用:
// 使用 Mock
var Mock = require('mockjs')
var data = Mock.mock({// 属性 list 的值是一个数组,其中含有 1 到 10 个元素'list|1-10': [{// 属性 id 是一个自增数,起始值为 1,每次增 1'id|+1': 1}]
})
// 输出结果
console.log(JSON.stringify(data, null, 4))
项目目录如下:
具体步骤:
【1】新建一个mock文件夹,定义一个index.js文件:
在 src下面创建一个mock目录,创建一个index.js文件,其它模拟的数据都放在和index.js文件同级,遍历所有mock下面的文件然后注册mock服务。
import Mock from 'mockjs'
// //开启mock
// window.EVN_CONFIG.baseApiUrl = "http://127.0.0.1:8080"
// window.EVN_CONFIG.ssoApiUrl = "http://127.0.0.1:8080"
// window.EVN_CONFIG.baseApiRoot = "/api"
// window.EVN_CONFIG.mock = true// 设置响应延时
Mock.setup({// 可以是整数,也可以是‘-’字符串timeout: '200-600'
})// const evnConfig = window.EVN_CONFIG
const evnConfig = {baseApiUrl: 'http://127.0.0.1:8080',ssoApiUrl: 'http://127.0.0.1:8080',baseApiRoot: '',// baseApiRoot: '/api',mock: true
}let configArray = []if (evnConfig.mock) {// 使用webpack的require.context()遍历所有的mock文件const files = require.context('.', true, /\.js$/)files.keys().forEach((key) => {// console.log("🚀 ~ file: index.js:43 ~ files.keys ~ key:", key)if (key === './index.js') return// configArray = configArray.concat(files(key).default)configArray = configArray.concat(files(key))// console.log("🚀 ~ file: index.js:43 ~ files.keys ~ files(key):", files(key))// console.log("🚀 ~ file: index.js:43 ~ files.keys ~ files(key).default:", files(key).default)// console.log("🚀 ~ file: index.js:43 ~ files.keys ~ configArray:", configArray)})// 注册所有的mock服务configArray.forEach((item) => {console.log("🚀 ~ file: index.js:45 ~ configArray.forEach ~ item:", item)let url = evnConfig.baseApiUrlurl += item.url/*** RegExp(url + '.*') 使用正则匹配URL* item.method 请求的方法 POST/GET/PUT/DELETE* (options) => {} 返回的函数* options 可以获取到 body, type, url*/Mock.mock(RegExp(url + '.*'), item.method, (options) => {console.debug(url, options)return Mock.mock(item.response)})})
}
【2】在main.js文件内引入:
import './mock/index'
【3】新建页面的mockjs文件,如tableLinkage.js:
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)// 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)const paramsMap = {'companyCodeList': 'companyCode'}const multipleArr = tableLinkageData.data.filter(item => {let key = 'companyCodeList'if (params[key].length === 0) {return true} else {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]}
})
可配合axios,封装使用,具体见这篇文章:简单封装axios(可配合mockjs使用)对请求方法进行二次封装-CSDN博客
这篇关于使用Mockjs模拟(假数据)接口(axios)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!