鴻蒙的橫向滾動選單和分組Group列表選單和fetch請求載入聚合資料
阿新 • • 發佈:2021-01-21
目錄:
本文的專案是通過遠端呼叫聚合資料製作一個新聞頁面.首先要明確以下幾點:
1.頁面載入的時候 使用者點選載入瀏覽什麼伺服器就載入什麼,若一下全部加載出來不僅對頁面佈局有負擔,而且對伺服器的負載也很大,造成伺服器資源浪費.
2.思路過程(以製作首頁為例): onInit首先載入拿到首頁資料;使用者點選那個選單載入那個選單的資料.
專案過程如下:
1.匯入鴻蒙的網路請求模組fetch (上篇文章也講到) 這裡需要重點注意的是:一定要到config.json中去看有沒有配置二級域名 不然看不到資料.例如我這裡是v.juhe.cn 下圖:
2.因為鴻蒙沒有視覺化視窗 ,因此我們可以製作一個除錯視覺化視窗.除錯完成後 再將其去掉 . 這個視窗的目的僅是讓自己通過視覺化視窗清楚明瞭的看到是否成功拿到資料,便於我們更好的跟蹤和除錯.(點選事件changemenu跳轉到js中 將當前點選的選單項賦值給currentIndex就做製作一個除錯視窗)具體程式碼及標註以下會詳細給出. 展示想過如下圖:
模擬器中的字樣來自於聚合資料給定的樣式:
js業務邏輯層:
import fetch from '@system.fetch'; export default { data: { title:'', currentIndex:0, type:"", bookdatas:[], //申明一個數組 menus:["首頁","新聞","影視","音樂","天氣","生活","體育","電競","娛樂","美食"] }, onInit() { fetch.fetch({ url:"http://v.juhe.cn/toutiao/index?type=top&key=401162c3e198047abc4d73d6f95aabbe", //v.juhe.cn一定要到config.json中去看有沒有配置二級域名responseType:"json", success:(resp)=>{ let datas=JSON.parse(resp.data); //轉換成json資料格式 this.title=datas.reason; this.bookdatas=datas.result.data; } } ) }, changemenu(event){ let clickindex=event.index; this.currentIndex=clickindex ; //當前點選的選單項賦值給currentIndex this.type=typeof clickindex; if(clickindex==0) { } else if(clickindex==1) { } } }
頁面渲染:
<div class="container"> <!--鴻蒙沒有橫向和垂直的滾頂檢視元件--> <tabs class="tabs" index="{{currentIndex}}" vertical="false" onchange="changemenu"> <tab-bar class="tab-bar" mode="scrollable"> <block for="{{menus}}"> <text>{{$item}}</text> </block> </tab-bar> <tab-content class="tab-content" scrollable="true"> <div class="oneview"> <list class="listview"> //運用列表展示資料 <block for="{{bookdatas}}"> <list-item class="list-item"> <text>{{$item.title}}</text> </list-item> </block> </list> </div> <div class="twoview"> <text>two</text> </div> </tab-content> </tabs> <div class="info"> <text class="txtview">{{currentIndex}} </text> //返回當前標 <text class="txtview">{{type}} </text> //返回當前下表的數值型別 <text class="txtview">{{title}} </text> //是否成功獲取資料 </div> </div>
css屬性設定:
.container{ width: 100%; height: 1200px; background-color: palegreen ; display: flex; flex-direction: column; } .tabs{ width: 100%; } .tab-content{ width: 100%; height: 80%; background-color: green; } .oneview{ width: 100%; height: 100%; background-color: white; } .twoview{ width: 100%; height: 100%; background-color: skyblue; } .info{ width: 100%; height: 20%; border:1px solid red; } .txtview{ font-size: 50px; color: red; } .listview{ width: 100%; height: 100%; } .list-item{ width: 100%; height: 20%; border: 1px solid red; }
最後再強調一點 在呼叫聚合資料的時候程式碼的格式一定要和聚合給定的格式相同,通俗的來講就是例如:我這裡想獲取的是是result中的data中的title的資料(見下圖) 因此我們同樣要將獲取的陣列放到申明的bookdatas陣列中
最終效果圖如下:
這樣專案的大體框架就出來了 其他頁面也是如此.後續會繼續優化頁面的佈局.
作者:noutsider
想了解更多內容,請訪問: 51CTO和華為官方戰略合作共建的鴻蒙技術社群https://harmonyos.51cto.com/