好的架構封裝,不只能夠加快開發的速度,還能使得邏輯更加簡明,不用關心內部的實現。在此介紹一下vue-resource基於es6出來的神器promise的封裝處理。(如今vue-resource官方已經再也不維護,推薦使用axios,固然axios也能夠這樣作相似處理)vue
首先抽出一個baseHttp.js,用於處理vue-resource的方法調用ios
import Vue from 'vue'
let vue = new Vue()
//GET請求,將url和請求參數傳入,經過Promise,將成功和失敗的數據派發出去
export function getHttp(url, params) {
return new Promise((resolve, reject) => {
vue
.$http({
url: url,
params: params,
method: 'GET'
})
.then(response => {
resolve(response.body)
}, response => {
reject(response.bodyText)
})
})
}
//POST請求,將url,請求參數和body傳入,經過Promise,將成功和失敗的數據派發出去
export function postHttp(url, params, body) {
return new Promise((resolve, reject) => {
vue
.$http({
url: url,
params: params,
body: JSON.stringify(body),
method: 'POST'
})
.then(response => {
resolve(response.body)
}, response => {
reject(response.bodyText)
})
})
}
複製代碼
核心部分已經講完了,就是這麼簡單。es6
而後寫一個net.js,用於處理須要的請求處理axios
Examplesapi
import {getHttp, postHttp} from './basehttp'
/** * GET請求 * 請求url爲app/user/{user_id}?aaaa=1234 **/
export function getUserInfo(userId) {
let url = 'app/user/{user_id}'
let params = {
user_id: userId,
aaaa: 1234
}
return getHttp(url, params)
}
/** * POST請求 * 請求app/user/query/{user_id}?aaaa=1234 * 請求body { serverId: String, scope: String } */
export function postUserInfo(userId, serverId, scope) {
let url = 'app/user/query/{user_id}'
let params = {
user_id: userId,
aaaa: 1234
}
let body = {
serverId: serverId,
scope: 'personal'
}
return postHttp(url, params, body)
}
複製代碼
調用promise
通過封裝後,調用就變得很是簡單了架構
import * as http from '../../api/net'
//getUserInfo調用
http.getUserInfo(userId)
.then(response => {
//成功處理
}, reject => {
//失敗處理
})
//postUserInfo
http.postUserInfo(userId, serverId, scope)
.then(response => {
//成功處理
}, reject => {
//失敗處理
})
複製代碼