把axios方法封装成一个个的函数,并统一在一个文件中:
>> allApis.js
import api from './myAxios'
// GET
export const getAllNavList = () => {
return api({
url: '...',
method: 'get'
})
}
// GET - 带参数
export const getAllNavList = (data) => {
return api({
url: '...',
method: 'get',
params: data
})
}
// POST
export const updateBannerSort = (data) => {
return api({
url: "/updateBannerSort",
method: "post",
data: data
});
};
// PUT
export const editBanner = (data) => {
return api({
url: "/editBanner",
method: "put",
data: data
});
};
// DELETE - id拼接的方式
export const deleteAdmin = (data) => {
return api({
url: "/deleteAdmin/"+data.userId,
method: "delete"
});
};
// 下载文件
export const recordDownload = (data) => {
return api({
url: "/downloadSignUpTable",
method: "post",
responseType: 'blob',
data: data
});
};
// 提交 - 包含文件类型 - formdata数据类型
export const addTempFile = (data) => {
let formdata = new FormData()
for(let itemkey in data) {
if(itemkey == 'files') {// 如果是文件,要先把每个文件单独转成FormData
let filesarr = data[itemkey];
for(let i =0; i < filesarr.length; i ++) {
formdata.append('files', filesarr[i])
}
}else {
formdata.append(itemkey, data[itemkey])
}
}
return api({
url: "/addTempFile",
method: "post",
data: formdata
});
};
封装后的api如何使用:
import { getProductArea } from '../HTTP/myApis'
methods: {
async initProductArea() {
await getProductArea({id: 1}).then(res => {
console.log(res.data)
})
}
}