详解Vue整合axios的实例代码
在vue开发中,不可避免要整合axios,简单记录一下整合中的文件,方便以后使用查找。
整合文件axios.js
importaxiosfrom'axios';
//适配vue-resource
constinstance=axios.create();
instance.interceptors.request.use(config=>{
//Serialize.decode(config);
returnconfig;
});
instance.interceptors.response.use(response=>{
returnresponse.data;
},err=>{
if(err.response){
axios.post('/v1/error',err.response);
returnPromise.reject(err.response.data);
}
returnPromise.reject({code:1024,message:err.message});
});
functionplugin(Vue){
if(plugin.installed){
return;
}
Vue.http=instance;
}
if(typeofwindow!=='undefined'&&window.Vue){
window.Vue.use(plugin);
}
exportdefaultplugin;
vue插件使用app.js
importVuefrom'vue';
importAppfrom'./App.vue';
importstorefrom'./store';
import{sync}from'vuex-router-sync';
importrouterfrom'./router';
import*asfiltersfrom'./filters';
importyxuifrom'yxui/dist/yxui.min';
importaxiosfrom'./axios';
Vue.use(yxui);
Vue.use(axios);
//synctherouterwiththevuexstore.
//thisregisters`store.state.route`
sync(store,router);
//registerglobalutilityfilters.
Object.keys(filters).forEach(key=>{
Vue.filter(key,filters[key]);
});
//createtheappinstance.
//hereweinjecttherouterandstoretoallchildcomponents,
//makingthemavailableeverywhereas`this.$router`and`this.$store`.
constapp=newVue({
router,
store,
...App
});
//exposetheapp,therouterandthestore.
//notewenotmountingtheapphere,sincebootstrappingwillbe
//differentdependingonwhetherweareinbrowserorontheserver.
export{app,router,store};
在vuexaction中使用:
actions:{
//adList
[TypesAds.AD_GET_LIST](ctx,params){
returnVue.http.get('/v1/api/ads/list',{params}).then(data=>{
ctx.commit(TypesAds.AD_GET_LIST,data);
returndata;
}).catch(err=>{
//统一错误处理
Vue.$message.error(err.msg);
});
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。