axios与vue的封装
var $axios = axios.create({
baseURL: 'http://localhost:8080/',
withCredentials: true,
});
if (Vue) {
Vue.prototype.$axios = $axios;
Vue.prototype.$ajax = function(getPromiseHandler) {
let promise = new Promise((resolve, reject) => {
try {
let loadIndex = layer.load();
getPromiseHandler
.then((response) => {
layer.close(loadIndex);
let result = response.data;
if (!result.hasOwnProperty("login")) {
resolve(result);
return;
}
if (!result.login) {
layer.msg('请登录后访问', {
icon: 7,
time: 1000
}, function() {
window.top.location.href = "../login/login.html"
});
return;
}
resolve(result);
})
.catch((err) => {
layer.close(loadIndex);
if (error.response) {
console.log(error.response.data);
layer.msg('请求出错', {
icon: 7,
time: 2000
});
} else {
layer.msg('系统升级中。。。', {
icon: 7,
time: 2000
});
console.log('Error', error.message);
}
console.log(error.config);
});
} catch (e) {
layer.close(loadIndex);
layer.msg('JavaScript代码错误:' + error.message, {
icon: 2,
time: 1500
});
}
});
return promise;
}
Vue.prototype.$myGet = function(url, config) {
let promise = new Promise((resolve, reject) => {
this.$ajax(this.$axios.get(url, config))
.then((result) => {
resolve(result);
});
});
return promise;
}
Vue.prototype.$myPost = function(url, data, config) {
let promise = new Promise((resolve, reject) => {
this.$ajax(this.$axios.post(url, data, config))
.then((result) => {
resolve(result);
});
});
return promise;
}
Vue.prototype.$myPut = function(url, data, config) {
let promise = new Promise((resolve, reject) => {
this.$ajax(this.$axios.put(url, data, config))
.then((result) => {
resolve(result);
});
});
return promise;
}
Vue.prototype.$myDelete = function(url, config) {
let promise = new Promise((resolve, reject) => {
this.$ajax(this.$axios.delete(url, config))
.then((result) => {
resolve(result);
});
});
return promise;
}
}