鴻蒙的橫向滾動菜單和分組Group列表菜單和fetch請求加載聚合數據
https://harmonyos.51cto.com/#zz
本文的項目是通過遠程調用聚合數據制作一個新聞頁面.首先要明確以下幾點:
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數組中


最終效果圖如下:

這樣項目的大體框架就出來了 其他頁面也是如此.后續會繼續優化頁面的布局.
©著作權歸作者和HarmonyOS技術社區共同所有,如需轉載,請注明出處,否則將追究法律責任。
https://harmonyos.51cto.com/#zz