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);
});
}
}
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。