vueリクエストパッケージスキーム


方案一config/fetch.js
import {
     
	baseUrl
} from './env'

//         
export default async(url = '', data = {
     }, type = 'GET', method = 'fetch') => {
     
	type = type.toUpperCase();
	url = baseUrl + url;

	if (type == 'GET') {
     
		let dataStr = ''; //       
		Object.keys(data).forEach(key => {
     
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
     
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}

	if (window.fetch && method == 'fetch') {
     
		let requestConfig = {
     
			credentials: 'include',
			method: type,
			headers: {
     
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},
			mode: "cors",
			cache: "force-cache"
		}

		if (type == 'POST') {
     
			Object.defineProperty(requestConfig, 'body', {
     
				value: JSON.stringify(data)
			})
		}
		
		try {
     
			const response = await fetch(url, requestConfig);
			const responseJson = await response.json();
			return responseJson
		} catch (error) {
     
			throw new Error(error)
		}
	} else {
     
		return new Promise((resolve, reject) => {
     
			let requestObj;
			if (window.XMLHttpRequest) {
     
				requestObj = new XMLHttpRequest();
			} else {
     
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST') {
     
				sendData = JSON.stringify(data);
			}

			requestObj.open(type, url, true);
			requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
     
				if (requestObj.readyState == 4) {
     
					if (requestObj.status == 200) {
     
						let obj = requestObj.response
						if (typeof obj !== 'object') {
     
							obj = JSON.parse(obj);
						}
						resolve(obj)
					} else {
     
						reject(requestObj)
					}
				}
			}
		})
	}
}

使用方法:service/getData.js
import fetch from '../config/fetch'
import {
     getStore} from '../config/mUtils'//             

export const hotcity = () => fetch('/v1/cities', {
     
	type: 'hot'
});

/**
 *          
 */
export const rePostVerify = (cart_id, sig, type) => fetch('/v1/carts/' + cart_id + '/verify_code', {
     
	sig,
	type,
}, 'POST');
/**
 *       
 */

export const getUser = () => fetch('/v1/user', {
     user_id: getStore('user_id')});
/**
 *         
 */

export const groupcity = () => fetch('/v1/cities', {
     
	type: 'group'
});


//async関数はPromiseオブジェクトを返し、thenメソッドを使用してコールバック関数を追加できます.関数が実行されるとawaitに遭遇すると先に戻り、トリガされた非同期操作が完了するまで待ってから、関数体内の後ろの文を実行します.だから
//      
 groupcity().then(res => {
     
     this.groupcity = res;
 })

または、
  async initData(){
     
                if (this.userInfo && this.userInfo.user_id) {
     
                    this.orderData = await getOrderDetail(this.userInfo.user_id, this.orderDetail.unique_id);
                    this.showLoading = false;
                    this.$nextTick(() => {
     
                        new BScroll('#scroll_section', {
       
                            deceleration: 0.001,
                            bounce: true,
                            swipeTime: 1800,
                            click: true,
                        }); 
                    })
                }
            },

シナリオ2