vue 元件的封裝之基於axios的ajax請求
阿新 • • 發佈:2019-02-09
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 }) }