Vue 中axios 封装(引用了vant的提示)

原创 leechee 随笔 axios 52阅读 7 天前 举报

import axios from 'axios';
import { Dialog, Toast } from 'vant';
import { router } from '../../router'
let instance = axios.create({
timeout: 6000,
baseURL: process.env.NODE_ENV === "development" ? '/api' : "http://yizhongyuan.gongjiayun.cn/";
});

instance.interceptors.response.use((res) => {
Toast.clear();
let data = res.data;
if (!data.success) {
if (data.error) {
Dialog.alert({
title: '警告',
message: data.error.code + ':' + data.error.message
});
}
return false;
}
return res;
}, (error) => {
//未登录检测
if (error.response.status == 403) {
Toast.clear();
localStorage.setItem('redirect', router.currentRoute.fullPath);
window.location.href = process.env.NODE_ENV === "development" ? '/api' : "/";
return Promise.reject(error);
}
else {
Toast.clear();
Dialog.alert({
title: '警告',
message: error.response.message
})
}
return Promise.reject(error);
});

const post = (url, data, config = {}) => {
return instance.post(url, data, config)
}

const put = (url, data, config = {}) => {
return instance.put(url, data, config)
}

const get = (url, params, config = {}) => {
return instance.get(url, {
params: params,
...config
})
}

const deleteMethod = (url, config = {}) => {
return instance({
url: url,
method: 'delete',
...config
})
}

export default {
install(Vue) {
Object.defineProperties(Vue.prototype, {
$reqGet: {
value: get
},
$reqPost: {
value: post
},
$reqPut: {
value: put
},
$reqDel: {
value: deleteMethod
},
})
}
}

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复