在vue中使用Promise对axios进行封装

根据各自公司需求进行修改

import md5 from '@/assets/js/md5.js'
import axios from 'axios'
import { Message } from 'element-ui';


let num = 0

export  const fath = (url,data,method,id,num) => {
	let aa
	if(num == 1) {
		aa = convertObjectToFormData(data, id ? id : '', 'A30D-634C-0A4F')	
	}else {
		aa = data
	}
	if(method == 'get') {
		return get(url,aa)
	}else if(method == 'post') {
		return post(url,aa)
	} else if (method == 'put') {
		return put(url,data)
	}
}
const post = (url,aa) => {
	return new Promise((resolve,reject) => {
		axios.interceptors.request.use(function(config) {
			let userinfo = JSON.parse(sessionStorage.getItem('userinfo'))
			if (userinfo.usercode) {
				config.headers.token = userinfo.usercode;
				return config;
			}
		}, function(error) {
			return Promise.reject(error);
		});
		axios.post(url,aa).then(res => {
			if(res.data.code == 0) {
				resolve(res.data)
				if(num == 0) {
					Message ({
					    message: '成功',
						duration:1000,
					    type: 'success'
					})
					num = 2
					let time = setInterval(() => {
						num--;
						if(num == 0) {
							clearTimeout(time);
						}
					},1000)
				}
			}else {
				Message.error(res.data.message)
				return
			}
		}).catch(res => {
			reject(res)
			Message.error('网络链接有误,请检查网络')
			return
		})
	})
}
const put = (url,data) => {
	return new Promise((resolve,reject) => {
		axios.interceptors.request.use(function(config) {
			let userinfo = JSON.parse(sessionStorage.getItem('userinfo'))
			if (userinfo.usercode) {
				config.headers.token = userinfo.usercode;
				return config;
			}
		}, function(error) {
			return Promise.reject(error);
		});
		axios.put(url,data).then(res => {
			if(res.data.code == 0) {
				resolve(res.data)
				// Message.error('成功')
				Message ({
				    message: '成功',
					duration:1000,
				    type: 'success'
				})
				// return Promise.
			}else {
				Message.error(res.data.message)
				return
			}
		}).catch(res => {
			reject(res)
			Message.error('网络链接有误,请检查网络')
			return
		})
	})
}
const get = (url,aa) => {
	return new Promise((resolve,reject) => {
		axios.interceptors.request.use(function(config) {
			let userinfo = JSON.parse(sessionStorage.getItem('userinfo'))
			if (userinfo.usercode) {
				config.headers.token = userinfo.usercode;
				return config;
			}
		}, function(error) {
			return Promise.reject(error);
		});
		axios.get(url,{ params: aa }).then(res => {
			if(res.data.code == 0) {
				resolve(res.data)
				Message ({
				    message: '成功',
					duration:1000,
				    type: 'success'
				})
			}else {
				Message.error(res.data.message)
				return
			}
		}).catch(res => {
			reject(res)
			Message.error('网络链接有误,请检查网络')
			return
		})
	})
}


function convertObjectToFormData(obj, id, key) {
	let arr = new Array();
	let i = 0;
	if (obj.hasOwnProperty('keyword')) {
		for (var attr in obj) {
			if (attr === 'keyword') {
				// let str = encodeURIComponent(obj[attr]).replace(/%20/g,'+').replace('(','%28').replace(')','%29').replace('*','%2A').replace('!','%21').replace('~','%7E')
				let str = encodeURIComponent(obj[attr]).replace(/%20/g, '+').replace('*', '%2A').replace('!', '%21').replace('~',
					'%7E')
				arr[i] = attr + "=" + str;
			} else {
				let str = encodeURIComponent(obj[attr]).replace(/%20/g, '+').replace('(', '%28').replace(')', '%29').replace('*',
					'%2A').replace('!', '%21').replace('~', '%7E')
				arr[i] = attr + "=" + str;
			}
			i++;
		}
	} else {
		for (var attr in obj) {
			let str = encodeURIComponent(obj[attr]).replace(/%20/g, '+').replace('(', '%28').replace(')', '%29').replace('*',
				'%2A').replace('!', '%21').replace('~', '%7E')
			arr[i] = attr + "=" + str;
			i++;
		}
	}


	arr = arr.sort();
	let str = arr.join("&");
	let sign = md5(str + ((id) ? id : "") + key)
	// console.log(str + `&sign=${sign}`)
	return str + `&sign=${sign}`;
}

在mian.js使用

axios.defaults.baseURL = '接口的前缀'//测试2
import {
	fath
} from '@/utils/index.js';
Vue.prototype.resFrom = {
	fath
};

在vue文件中可以直接使用this☞向resFrom这个方法

this.resFrom.fath('backend/asOrders/'+ this.pageData.id +'/assign.do',data,'put','',0).then((res) => {
						if(res.code == 0) {
							 // this.$emit('funcing', this.cofShowNum);
							 this.$emit('func', this.cofShowNum);
						} 
					})
在vuex中就不能使用this,因此可以使用引入import
import {
		fath
	} from '@/utils/index.js'
const state = {
	appletCouponData:[],
	GetBindData:[],
}

const mutations = {
	APPLETCOUPON(state,data) {
		state.appletCouponData = data
	},
	COUPONGETBIND(state,data) {
		state.GetBindData = data
	},
}

const actions = {
async appletCoupon({ commit },data) {
	let res = await fath('backend/car/wash/applet/coupon/get.do',data,'get','',0)
	commit('APPLETCOUPON',res.resultData)
},
// 获取详情
async couponGetBind({ commit },data) {
	let res = await fath('backend/car/wash/applet/coupon/getBind.do',data,'get','',0)
	commit('COUPONGETBIND',res.resultData.items)
},
}

const getters = {
	GetappletCouponData(state) {
		return state.appletCouponData
	},
	GetGetBindData(state) {
		return state.GetBindData
	},
}

const manageCarCouponModule = {
  state,
  mutations,
  actions,
  getters
}

export default manageCarCouponModule


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值