為什麼應該在uni-app專案裡使用luch-request?

uni-app 是一個使用 Vue。js 開發所有前端應用的框架,開發者編寫一套程式碼,可釋出到iOS、Android、H5、以及各種小程式(微信/支付寶/百度/頭條/QQ/釘釘/淘寶)、快應用等多個平臺。

專案的開發離不開

資料互動

,一個好的request請求庫可以讓我們的開發事半功倍。uni-app也不例外,uni。request只提供基礎請求功能,無法達到專案開發的要求,luch-request應運而生。

為什麼應該在uni-app專案裡使用luch-request?

luch-request官網

luch-request是什麼?

luch-request 是一個基於Promise 開發的uni-app跨平臺、專案級別的請求庫,它有更小的體積,易用的api,方便簡單的自定義能力。

luch-request誕生於19-05月,至今已迭代20多個版本。DCloud外掛市場request類外掛下載量第一。支援npm下載。

它能為我們解決什麼問題?

支援全域性掛載

支援多個全域性配置例項

支援自定義驗證器

支援檔案上傳/下載

支援task 操作

支援自定義引數

支援多請求攔截器/響應攔截器

對引數的處理比uni。request 更強

也許你還不明白這些有什麼用。但是他卻對應著我們開發中一個一個的痛點。

你的資料獲取方式

uni。request({ url: this。$baseUrl + ‘api/user?arg1=data1’ method: ‘POST’, data: {id:1}, header: {Content-Type: ‘。。。’, token: ‘。。。。’} success: (res) => {}, fail: (err) => {}})

使用luch-request後

this。$http。post(‘/api/user’, { id: 1}, { params: { arg1: data1 }})。then(res => { 。。。})。catch(err => { 。。。})

它有什麼優勢?

條件編譯開發:

減少程式碼體積,減少開發中debug時的誤導影響。看不到對應終端額外的引數。

極易的自定義能力:

有些外掛會把loading、auth等引數加入配置,使其做一些請求之外的操作,這些配置並不是所有人都會使用。

request請求庫只需專注於請求即可

。luch-request對額外操作的處理則更為優雅,增加了` custom `配置,使開發者可以做一些自定義操作。

http。setConfig((config) => { /* config 為預設全域性配置*/ config。baseURL = ‘http://www。quanzhan。co’ /* 根域名 */ config。custom = { loading: true // 預設有loading } return config})http。interceptors。request。use((config) => { /* 請求之前攔截器。可以使用async await 做非同步操作 */ config。header = { 。。。config。header, a: 1 // 演示攔截器header加參 } // 演示custom 用處 if (config。custom。loading) { uni。showLoading() } return config}, (config) => { return Promise。reject(config)})http。interceptors。response。use(async (response) => { /* 請求之後攔截器。可以使用async await 做非同步操作 */ // if (response。data。code !== 200) { // 服務端返回的狀態碼不等於200,則reject() // return Promise。reject(response) // } if (response。config。custom。loading) { uni。hideLoading() } return response}, (response) => { // 請求錯誤做點什麼。可以使用async await 做非同步操作 console。log(response) if (response。config。custom。loading) { uni。hideLoading() } return Promise。reject(response)})// 單介面不想要loadinghttp。get(‘user/list’, {custom: {loading: false}})http。post(‘user/list’, {}, {custom: {loading: false}})

易用的api設計:

部分api設計為降低學習成本,參照axios設計。並擴充套件一些其它的api,入門更加容易。

...

快速上手

npm

npm i luch-request -S

cli 使用者使用npm 包需增加以下配置

專案根路徑下建立vue。config。js 檔案,增加以下內容

// vue。config。js module。exports = { transpileDependencies: [‘luch-request’] }

GitHub

https://github。com/lei-mu/luch-request

使用DCloud/luch-request 資料夾即可

DCloud外掛市場

https://ext。dcloud。net。cn/plugin?id=392

為什麼應該在uni-app專案裡使用luch-request?

luch-request DCloud 外掛市場

luch-request官網

https://www。quanzhan。co/luch-request/

https://www。quanzhan。co/luch-request/

為什麼應該在uni-app專案裡使用luch-request?

luch的部落格網站logo

更新歷史

https://github。com/lei-mu/luch-request/releases