vue 组件的封装之基于axios的ajax请求方法

如下所示:

import Vue from 'vue'
 
let service = {
 url: 'http://host.xxxxx.com/xxx.php'
}
 
service.ajaxReuqest = (url, options, type, fileFlag) => {
 for (const i in options) {
 if (!options[i] && options[i] !== 0 && (options[i].length && options[i].length > 0)) {
  delete options[i]
 }
 }
 let promise = new Promise((resolve, reject) => {
 if (fileFlag) {
  Vue.axios.post(url, options, {
  headers: {
   'Content-Type': 'multipart/form-data'
  }
  }).then((res) => {
  resolve(res)
  })
 } else if (type === 'GET') {
  Vue.axios.get(url, { params: options }).then((res) => {
  resolve(res.data.resultObj)
  }).then((err) => {
  reject(err)
  })
 } else {
  Vue.axios.post(url, options).then((res) => {
  resolve(res)
  }).then((err) => {
  reject(err)
  })
 }
 })
 return promise
}

支持POST GET请求以及图片上传,基于axios,适用于vue,

以异步获取省份列表作为例子:

// 获取省份信息
service.getProvinceList = (options) => {
 return service.ajaxRequest(service.url + '/basic/getProvinceList', options, 'POST')
}
getProvinceList () {
 service.getProvinceList({}).then((res) => {
  this.provinceList = res.data.resultObj.data
 })
}

相关推荐