Vue---axios二次封装
程序员文章站
2022-03-27 11:49:02
axios二次封装// 使用数据拦截器import axios from 'axios';import { Message } from "element-ui";axios.defaults.timeout = 5000;axios.defaults.withCredentials=true;// axios.defaults.baseURL = '/api'; //填写域名 跨域//options里面需要url和data参数//code和msg根据实际返回字段值更改即可expo....
- axios二次封装
// 使用数据拦截器
import axios from 'axios';
import { Message } from "element-ui";
axios.defaults.timeout = 5000;
axios.defaults.withCredentials=true;
// axios.defaults.baseURL = '/api'; //填写域名 跨域
//options里面需要url和data参数
//code和msg根据实际返回字段值更改即可
export default {
get(options) {
return new Promise((resolve, reject) => {
let getTimestamp = new Date().getTime()
axios.get(options.url + "?timestamp=" + getTimestamp, {
params: options.data || ''
}).then((response) => {
if (response.status == 200) { //成功
let res = response.data;
let { code, msg } = res;
if (code == '200') {
resolve(res)
} else {
Message({
showClose: true,
message: msg,
type: 'error'
});
}
} else {
reject(response.data)
}
}).catch(response => {
})
})
},
post(options) {
return new Promise((resolve, reject) => {
axios.post(options.url,
options.data || ''
).then((response) => {
if (response.status == 200) { //成功
let res = response.data;
let { code, msg } = res;
if (code == '200') {
resolve(res)
} else {
Message({
showClose: true,
message: msg,
type: 'error'
});
}
} else {
reject(response.data)
}
}).catch(response => {
})
})
}
}
- 在main.js中将封装好的axios挂载到Vue原型上
import Axios from "@/common/axios" //路径根据实际路径做修改
Vue.prototype.$axios = Axios;
- 调用
this.$axios.get({
url : 'xxxxxxxxxx',
data : {},
}).then(resu => {
//处理数据
});
this.$axios.post({
url : 'xxxxxxxxxx',
data : {},
}).then(resu => {
//处理数据
});
本文地址:https://blog.csdn.net/qq_39115469/article/details/108156192