前言
在小程序的開發中,實現長列表的數據展示和切換,一般都會選擇 swiper 和 scroll-view 配合實現,原因無他,個人覺得就是用戶體驗好,開發快速、方便,但也不是毫無詬病
比如很棘手的問題: swiper 的高度問題
Part.1 需要實現的需求
Part.2 實現步驟
上面展示的效果就是選擇 swiper 和 scroll-view 配合實現,接下來詳細說明下產出過程:
首先,我把頁面分為了兩個部分,分別是 紅色框內的內容 和 藍色框內的內容,相信想使用 swiper 實現列表的同學已經遇到了這個棘手的問題:swiper的高度一直是 150px,它無法根據內容的大小自適應,除非自己手動設置其高度
這就讓人很煩惱了,不知道其它同學怎么想,至少於我而言關於頁面布局 能用 CSS 實現的打死也不用 JS ,所以自己研究了一波,沒什么頭緒就搜索了一波,發現至少暫時這個問題還真得需要 js 實現,😂
那就開始干吧
1. 實現頭部:頭部布局沒什么說明的,就是有一點:使用 scroll-view 實現tab頭部選項的時(如:星期一,星期二,星期三....),scroll-view 的子元素不會自動橫着排列需要點 css支持~
分別為: white-space: nowrap 和 display: inline-block
如:
1 <view class="nav-box"> 2 <scroll-view class="tab-bar" :scroll-x="true" scroll-with-animation="true" :scroll-into-view="'tab_' + tabIndex"> 3 <view class="tab-item" 4 v-for="(tab,index) in tabList" 5 :key="tab.id" 6 :id="'tab_' + index" 7 @click="selectTitle(index)"> 8 <text class="tab-item-title" 9 :class="tabIndex == index? 'active' : ''">{{tab.name}}</text> 10 </view> 11 </scroll-view> 12 </view>
.nav-box { white-space: nowrap; // 文本強制不換行 background-color: #FFFFFF; .tab-bar { width: 750upx; height: 84upx; display: flex; .tab-item { height: 100%; padding: 0 30upx; display: inline-block; // 塊級元素設置為行級元素 .tab-item-title { line-height: 84upx; &.active { font-weight: bold; color: #1468FF; } } } } }
2. 實現列表數據區(原理:利用API獲取當前設備的屏幕可見區高度 - 頭部紅色框區域的高度 = 動態給swiper的高度),給 swiper 設置好高度之后利用 swiper-item 嵌套 scroll-view 的內容進行滑動,
‘上滑加載新數據’ - 放棄使用滑動到底部的 onReachBottom 事件來觸發,改用 scroll-view 的 @scrolltolower 事件觸發
‘下拉刷新’ - 放棄使用 onPullDownRefresh 事件來觸發,開啟 scroll-view 的自定義下拉刷新 refresher-enabled,具體可查看官方API( https://uniapp.dcloud.io/component/scroll-view )
注意:開啟下拉刷新時還涉及到一個很細節的地方,如果 scroll-view 組件的高度是動態設置的話,初始值不能設為 0 ,否則在小程序端會導致下拉刷新操作拉不下來,建議設置一個大於 100 的值~
如:
設置 swiper 的高度(我當前的項目值,僅供參考)
1 const res = uni.getSystemInfoSync(); 2 this.swiperH = (res.windowHeight - uni.upx2px(210));
使用 swiper-item 嵌套 scroll-view 的內容
1 <swiper class="swiper" 2 :style="{'height': swiperH + 'px'}" 3 :current="tabIndex" 4 @change="swiperChange" 5 duration="100"> 6 <swiper-item v-for="(item, index) in tabList" 7 class="swiper-item" 8 :key="index" 9 scroll-with-animation="true"> 10 <scroll-view class="swiper-item-scroll" 11 scroll-y="true" 12 :style="{'height': swiperH + 'px'}" 13 refresher-enabled 14 :refresher-triggered="triggered" 15 :refresher-threshold="80" 16 @refresherrefresh="onRefresh" 17 @scrolltolower="scrolltolower"> 18 <!-- 內容組件--> 19 <goodsItem ref="goodsItem"></goodsItem> 20 </scroll-view> 21 </swiper-item> 22 </swiper>
特此記錄一波 ~~~