vue中封装axios方法

时间:2024-04-30 13:07:44

axios基本配置 使用方法

import axios from 'axios'

// 创建axios实例
const service = axios.create({
baseURL: process.env.BASE_API, // node环境的不同,对应不同的baseURL
timeout: 5000, // 请求的超时时间
//设置默认请求头,使post请求发送的是formdata格式数据// axios的header默认的Content-Type好像是'application/json;charset=UTF-8',我的项目都是用json格式传输,如果需要更改的话,可以用这种方式修改
// headers: {
// "Content-Type": "application/x-www-form-urlencoded"
// },
withCredentials: true // 允许携带cookie
})

封装get和post方法

import axios from 'axios';
const serverconfig = require('../../static/serverconfig.json') // 这个json文件中配置接口根目录地址 class Axios{
getUrl(url){
return `${serverconfig.ApiUrl}${url}`; // 获取完整的接口地址
}; // post 请求
postServer(opt) {
const _axios = axios.create({
timeout: 10000
});
let data = {};
if (opt.data) {
data = opt.data;
}
_axios.post(opt.url, data).then((response) => {
console.log(response);
if(response.data.status === 'error'){
// 这里用layer弹层插件
layer.open({
content: 'error:' + response.data.hotelInfo
,skin: 'msg'
,time: 2 //2秒后自动关闭
});
if (opt.onFailed) {
opt.onFailed(response);
}
return;
}
if (opt.onSuccess) {
opt.onSuccess(response);
}
}).catch(error => {
if (opt.onFailed) {
opt.onFailed(error);
}
if (!error.response.data.success) {
alert(error.response.data.error.message);
// return;
} });
} // get 请求
getServer(opt) {
const _axios = axios.create({
timeout:10000
});
let data = {};
if (opt.data) {
data = opt.data;
}
_axios.get(opt.url, {params: data}).then((response) => {
if (opt.onSuccess) {
opt.onSuccess(response);
}
}).catch(error => {
if (opt.onFailed) {
opt.onFailed(error);
}
});
} setData(opt) {
let data = {};
if (opt.data) {
data = opt.data;
}
return data;
} } export default Axios;

封装接口

hotel.service.js
import Axios from  './axios.service'
const AxiosMethods = new Axios();
sendQueryServer(opt){
const data = AxiosMethods .setData(opt);
const url = AxiosMethods .getUrl('/Home/Query');
AxiosMethods .postServer({url, data, onSuccess: opt.onSuccess,
onFailed: opt.onFailed});
}
}

页面调用query.vue

 import HotelServer from "@/service/hotel.service"

const hotelServer = new HotelServer();

methods:{
_sendQueryServer() {
const loadingIndex = this.loadingShow()
hotelServer.sendQueryServer({
onSuccess: (res) => {
layer.close(loadingIndex)
console.log(res)
},
onFailed: (res) => {
layer.close(loadingIndex)
}
})
}