標籤:

在mpvue中如何優雅的封裝ajax?

昨天看到mpvue,今天試了一下。

發現不能直接引用axios

各位老大們是如何封裝ajax的?


簡單的封裝:

const fetch = function(url, options = {}) {
const { method = "GET", body = {}, showError = true } = options;

return new Promise((resolve, reject) =&> {
wx.request({
url,
data: body,
method,
header: {
"content-type": "application/json"
},
success: res =&> {
if (showError) {
if (res.statusCode &< 200 || res.statusCode &> 300) {
return reject(res.data || {});
}

if (Number(res.data.status) !== 0) {
return reject(res.data || {});
}
}

return resolve(res.data || {});
},
complete: res =&> {
// TODO:
}
});
});
};


怎麼封裝跟mpvue沒太大的關係,

簡單封裝了一個 可能有bug

const request = (opts, cb) =&> {
return new Promise((resolve, reject) =&> {
wx.request({
...opts,
success(res) {
opts.success(res)
resolve(res)
},
fail(err) {
opts.fail(err)
reject(err)
},
complete(res) {
cb cb(res)
}
})
})
}

class Http {
constructor(opts) {
this.interceptors = {
request: () =&> {},
response: () =&> {}
}
if (opts) {
this.root = opts.root
this.header = opts.header
if(this.interceptors) {
this.interceptors.request = opts.interceptors.request
this.interceptors.response = opts.interceptors.response
}
}

const methodList = [get, post, put, patch, delete]
const initConfig = {
header: {},
interceptors: {
response: () =&> {},
request: () =&> {}
}
}
methodList.forEach(item =&> {
this[item] = (url, data, config = { interceptors: {} }) =&> {

const mergedConfig = {
header: config[header] ? config[header] : this.header,
interceptors: {
response: config[interceptors] config[interceptors][response] ? config[interceptors][response] : this.interceptors.response,
request: config[interceptors] config[interceptors][request] ? config[interceptors][request] : this.interceptors.request,
},
}

const requestData = {
method: item.toUpperCase(),
url: this.root + url,
data,
success: mergedConfig.interceptors.response,
fail: mergedConfig.interceptors.response,
header: mergedConfig.header
}

mergedConfig.interceptors.request(requestData)
return request(requestData)
}
})
}
}

module.exports = Http

使用

const http = new Http()
http.root = PREFIX // 設置根路徑

// 請求攔截
http.interceptors.request = (data) =&> {
console.log(before request, data)
}
// 響應攔截
http.interceptors.response = (data) =&> {
console.log(before response, data)
if (data.statusCode &>= 500) {
toastErr(伺服器錯誤)
}
}
// 設置全局請求頭
http.header = {

};
// 請求
http.post(/user, { name: music }).then(res =&> {})


用promise封裝下wx.request吧,ajax行不通


微信裡面是 wx.request


推薦閱讀:

TAG:Vuejs | mpvue |