axios带有请求拦截器,避免在每个请求里面加loading重复操作,可以封装进去,在请求开始时加载loading层,请求结束关闭,loading层用vux的loading加载
axios.js
import axios from 'axios'
import Vue from 'vue' // 超时时间
axios.defaults.timeout = 15000;
// axios.defaults.withCredentials=true;
// http请求拦截器
axios.interceptors.request.use(config => {
Vue.$vux.loading.show({
text: 'Loading'
})
return config
}, error => {
setTimeout(() => {
Vue.$vux.loading.hide();
Vue.$vux.toast.text('加载超时', 'middle')
},3000)
return Promise.reject(error)
})
// http响应拦截器
axios.interceptors.response.use(data => {// 响应成功关闭loading
Vue.$vux.loading.hide()
return data
}, error => {
setTimeout(() => {
Vue.$vux.loading.hide()
Vue.$vux.toast.text('请求失败', 'middle')
},1000)
return Promise.reject(error)
}) export default axios;
封装get和post方法 axios.service.js
import axios from './axios'; class myAxios{ getUrl(url){
return `${__ce.baseURL}${url}`; // 打包时用这个 __ce.baseURL
// return `/api${url}`; // 防止跨域,开发环境用这个代理
}; //公共ajax;
postServer(opt) { let data = {};
if (opt.data) {
data = opt.data;
}
axios.post(opt.url, data).then((response) => {
console.log(response);
if(!response.data.status){
return;
}
if (opt.onSuccess) {
opt.onSuccess(response);
}
}).catch(error => {
if (opt.onFailed) {
opt.onFailed(error);
}
});
} // get 请求
getServer(opt) {
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 myAxios;
封装方法~
import myAxios from './axios.service'
const myAxiosMethods = new myAxios(); class RecordServer{ // 查询订单 -- post方法
sendMiceIndentSearchServer(opt){
const data = myAxiosMethods.setData(opt);
const url = myAxiosMethods.getUrl('/search');// 这里的/search是后端给的接口地址
myAxiosMethods.postServer({url, data, onSuccess: opt.onSuccess, onFailed: opt.onFailed});
} export default RecordServer;
在页面中使用
const recordSever = new RecordServer() methods:{
_sendSearchServer(){ // 在需要的地方调用这个方法
recordServer.sendSearchServer({
data: this.params, // params是这个接口需要传递给后台的参数
onSuccess: (res) => {
console.log(res)
},
onFailed: (err) => {
console.log(err)
}
})
}
}