本篇在《
UniApp入門教程- 項目創建》基礎上,對首頁信息數據進行動態綁定,封裝了http請求並對請求API進行集中管理
使用uView的Api請求工具
https://v1.uviewui.com/js/http.html
該插件適用於一般的請求場景,只支持post,get,put,delete請求,不適用於上傳下載,插件定位小而美,而不是大而全
首先在項目中創建文件夾“common”,新建兩個文件“
http.api.js”,"
http.interception.js"
其中http.api.js用來封裝常用的請求地址,http.interceptor.js 配置文件和攔截器相關代碼

http.api.js:
let indexUrl = '/api/index'; const install = (Vue, vm) => { // 此處沒有使用傳入的params參數 let index = (params = {}) => vm.$u.get(indexUrl ); vm.$u.api = { index }; //或者寫成 //vm.$u.api={} //vm.$u.api.authIndex=params=>vm.$u.post('/api/auth/login',params) } export default { install }
http.interceptor.js:
1 const install = (Vue, vm) => { 2 // 此為自定義配置參數,具體參數見上方說明 3 Vue.prototype.$u.http.setConfig({ 4 5 baseUrl: 'http://localhost:5030', // 請求的本域名 6 method: 'POST', 7 // 設置為json,返回后會對數據進行一次JSON.parse() 8 dataType: 'json', 9 showLoading: true, // 是否顯示請求中的loading 10 loadingText: '請求中...', // 請求loading中的文字提示 11 loadingTime: 800, // 在此時間內,請求還沒回來的話,就顯示加載中動畫,單位ms 12 originalData: false, // 是否在攔截器中返回服務端的原始數據 13 loadingMask: true, // 展示loading的時候,是否給一個透明的蒙層,防止觸摸穿透 14 // 配置請求頭信息 15 header: { 16 'content-type': 'application/json;charset=UTF-8' 17 }, 18 }); 19 20 // 請求攔截部分,如配置,每次請求前都會執行,見上方說明 21 Vue.prototype.$u.http.interceptor.request = (config) => { 22 // ...... 23 return config; 24 } 25 26 // 響應攔截,如配置,每次請求結束都會執行本方法 27 Vue.prototype.$u.http.interceptor.response = (res) => { 28 console.log(res); 29 return res; 30 if (res.code == 200) { 31 // res為服務端返回值,可能有code,result等字段 32 // 這里對res.result進行返回,將會在this.$u.post(url).then(res => {})的then回調中的res的到 33 // 如果配置了originalData為true,請留意這里的返回值 34 return res.result; 35 } else { 36 // 如果返回false,則會調用Promise的reject回調, 37 // 並將進入this.$u.post(url).then().catch(res=>{})的catch回調中,res為服務端的返回值 38 return false; 39 } 40 } 41 } 42 43 export default { 44 install 45 }
main.js 配置:
1 // http接口API集中管理引入部分 2 import httpApi from '@/common/http.api.js' 3 Vue.use(httpApi, app) 4 5 // http攔截器,此為需要加入的內容,如果不是寫在common目錄,請自行修改引入路徑 6 import httpInterceptor from '@/common/http.interceptor.js' 7 // 這里需要寫在最后,是為了等Vue創建對象完成,引入"app"對象(也即頁面的"this"實例) 8 Vue.use(httpInterceptor, app)
在上一篇《
UniApp入門教程- 項目創建》中,修改首頁中的行業咨詢,使得數據動態綁定
在本地運行接口項目,這里以.net core api為例

在http.api.js中添加請求Url:

找到pages->index->index.vue,在onload方法中添加請求,綁定數據


顯示效果如下:

但光加載數據還遠遠不夠,后續會對列表進行組件封裝,父子組件的通信,使其更加簡潔,擴展性更強。
增加下拉加載更多等優化用戶體驗的功能。
以上,僅用於學習和總結!