注:该方法使用场景为:axios以及mockjs,原生Ajax请求也可同理
1.插件准备
npm 模式
npm install axios
npm install mockjs
yarn 模式
yarn add axios
yarn add mockjs
2.请求方法封装
requestMethod.js
报错提示根据实际项目的使用修改
import axios from 'axios';
export default {
// get请求
get(url, params = {}, that, isMock = false) {
url = isMock `/mock${url}` : url
return new Promise((resolve, reject) => {
axios.get(url, {
params
})
.then(res => {
resolve(res)
})
.catch(error => {
that.$Notify({
type: "danger",
message: error.response.data.msg || "请求失败",
});
reject(error)
})
})
},
// post请求
post(url, data, that, isMock = false) {
url = isMock `/mock${url}` : url
return new Promise((resolve, reject) => {
axios.post(url, {
data
})
.then(res => {
resolve(res)
})
.catch(error => {
that.$Notify({
type: "danger",
message: error.response.data.msg || "请求失败",
});
reject(error)
})
})
},
// put请求
put(url, data, that, isMock = false) {
url = isMock `/mock${url}` : url
return new Promise((resolve, reject) => {
axios.put(url, {
data
})
.then(res => {
resolve(res)
})
.catch(error => {
that.$Notify({
type: "danger",
message: error.response.data.msg || "请求失败",
});
reject(error)
})
})
},
// 删除请求
delete(url, data, that, isMock = false) {
url = isMock `/mock${url}` : url
return new Promise((resolve, reject) => {
axios.delete(url, {
data
})
.then(res => {
resolve(res)
})
.catch(error => {
that.$Notify({
type: "danger",
message: error.response.data.msg || "请求失败",
});
reject(error)
})
})
},
}
3.将请求方法引用到main.js中
import requestMethod from '@/request/requestMethod'
app.config.globalProperties.$httpRequest = requestMethod;
4.mock封装
文件格式如下:
flowchart LR
mockData --> data --> mockDemo.js
mockData --> index.js
mockData --> mockBaseFunction.js
mockBaseFunction.js
封装了一些数据增删改查的方法
import Mock from 'mockjs'
export default {
mock: Mock.mock, //这里定义mock变量,是为了方便其他成员使用mockjs,不需要再自己引用mockjs,直接引用mockBaseFunction.js即可
// 将url转换成/mock+url格式
getMockUrl(url) {
return `/mock${url}`
},
// 将请求的传参转换成js对象
getOptions(options) {
return JSON.parse(options.body)
},
// 查询模拟数据
queryMockData(option, mockData, selfFunction) {
if (typeof (selfFunction) !== 'function') {
return mockData
}
return selfFunction()
},
// 模拟新增数据
addMockData(options, mockData, successData = {}, selfFunction) {
const params = this.getOptions(options)
if (typeof (selfFunction) !== 'function') {
params.id = mockData.data.rows.length + 1
mockData.data.rows.push(params)
return successData || ''
}
return selfFunction()
},
// 模拟编辑数据
updateMockData(options, mockData, successData = {}, selfFunction) {
if (typeof (selfFunction) !== 'function') {
const obj = this.getOptions(options)
mockData.data.rows = mockData.data.rows.map(item => {
return item.id === obj.id obj : item
})
return successData || ''
}
return selfFunction()
},
// 模拟删除数据
deleteMockData(options, mockData, successData = {}, selfFunction) {
if (typeof (selfFunction) !== 'function') {
const id = parseInt(this.getOptions(options).id)
mockData.data.rows = mockData.data.rows.filter(item => {
return item.id !== id
})
return successData || ''
}
selfFunction()
}
}
index.js
读取data里面的mock接口
(function () {
const mockData = require.context('../mockData/data', false, /[A-Za-z0-9-_,\s]+\.js$/i)
mockData.keys().reduce((modules, modulePath) => {
// set './app.js' => 'app'
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '')
const value = mockData(modulePath)
modules[moduleName] = value.default
return modules[moduleName][moduleName]()
}, {})
})()
mockDemo.js
mock demo数据,根据需要,封装不同模块mock数据
import mockBaseFunction from '../mockBaseFunction'
const successData = {
data: null,
code: 200,
msg: "success",
success: true,
}
const itemPriceInfo = mockBaseFunction.mock({
code: 200,
msg: "success",
success: true,
result: {
'rows|5': [{
category: '@name()', // '@name()随机生成英文名字'
createdByName: '@cname()', // '@name()随机生成中文名字'
'id|+1': 63, // "id|+number":number 生成的每个id比前面一个大number
manufacturerName: '@ctitle()',
'status|1-3': 3, // "status1-3"随机生成1-3中的某个整数
supplierCompanyId: 61,
supplierCompanyName: '@ctitle()', // '@ctitle()'随机生成中文标题
}],
pageResponse: {
start: 0,
limit: 5,
results: 60
}
},
})
export default {
mockDemo() {
// 拦截的url:fun.getMockUrl('需要拦截的url'),请求方法,可为空:'',拦截后的操作方法
// 拦截get请求,返回模拟数据
mockBaseFunction.mock(RegExp(mockBaseFunction.getMockUrl('/api/web/itemPrice/findFinalPriceOfferPage') + '.*'), 'get', function (options) {
return mockBaseFunction.queryMockData(options, itemPriceInfo)
})
// 拦截post请求,增加数据,拦截后返回增加模拟数据方法
mockBaseFunction.mock(mockBaseFunction.getMockUrl('/api/userInfo/addUser'), 'post', function (options) {
mockBaseFunction.addMockData(options, itemPriceInfo, successData)
})
// 拦截post请求,修改数据,拦截后返回修改模拟数据方法
mockBaseFunction.mock(mockBaseFunction.getMockUrl('/api/userInfo/updateUser'), 'post', function (options) {
mockBaseFunction.updateMockData(options, itemPriceInfo, successData)
})
// 拦截post请求,删除数据,拦截后返回删除模拟数据方法
mockBaseFunction.mock(mockBaseFunction.getMockUrl('/api/userInfo/deleteUser'), 'post', function (options) {
mockBaseFunction.deleteMockData(options, itemPriceInfo, successData)
})
}
}
5.mock接口引入main.js
require('@/request/mockData/index')
6.使用
const queryRegistration = async () => {
const res = await proxy.$httpRequest.get(
'/api/web/itemPrice/findFinalPriceOfferPage',
{},
proxy,
true
);
console.log('res',res)
};
具体mock使用,参见 在项目中使用mockjs