axios
首先安装依赖:
cnpm install axios -D
在main.js中引入:
import axios from "axios";
在vue中使用axios进行交互时,axios提供了一些可配置项来方便管理,以下作部分记录以便后续使用
一般在进行交互(发送请求)时,为了用户友好,会有loading的效果,可通过axios进行统一配置
发送请求数据的时:
axios.interceptors.request.use(
function(config) {
store.dispatch("showLoading");//通过VUEX管理是否显示loading
return config;
},
function(error) {
return Promise.reject(error);
}
);
请求结束回来时:
axios.interceptors.response.use(
function(response) {
store.dispatch("hideLoading");
return response;
},
function(error) {
return Promise.reject(error);
}
);
post请求设置默认头部信息:
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
配置请求的根路径:
axios.defaults.baseURL = (process.env.NODE_ENV !=='production' ? config.dev.httpUrl:config.build.httpUrl)
例如:
axios.defaults.baseURL='http://localhost:8082/
挂载/暴露到VUE原型上,以便其他页面使用:
Vue.prototype.$http = axios;
其他页面使用时,可直接写为:
this.$http.get(url).then(res=>{
//成功操作
}).catch(error=>{
//失败操作
})
vue-resource
首先要安装vue-resource:
cnpm install vue-resource -D
在main.js中引入并使用:
import VueResource from "vue-resource";
Vue.use(VueResource);
请求前后配置,比如请求前显示loading,请求后消失:
Vue.http.interceptors.push((request, next) => {
store.dispatch("showLoading");
next(response => {
store.dispatch("hideLoading");
return response;
});
});
在其他组件中可以直接通过以下方式调用:
this.$http.get();
get请求:
this.$http.get('/someUrl', [options]).then(function(response){
// 响应成功回调
}, function(error){
// 响应错误回调
});
post请求:
this.$http.get('/someUrl',params, [options]).then(function(response){
// 响应成功回调
}, function(error){
// 响应错误回调
});