本文以一個(gè)簡(jiǎn)單的小例子,簡(jiǎn)述在微信小程序開(kāi)發(fā)中左右布局功能的實(shí)現(xiàn)方式,主要涉及scroll-view ,列表數(shù)據(jù)綁定,及簡(jiǎn)單樣式等內(nèi)容,僅供學(xué)習(xí)分享使用。
概述
在微信小程序開(kāi)發(fā)中,左右分欄(左邊顯示分類,右邊顯示明細(xì),然后進(jìn)行聯(lián)動(dòng))是一種常見(jiàn)的布局方式,多應(yīng)用于點(diǎn)餐,冷飲店,外賣,以及其他類似的商城。
布局分析
布局分析圖示如下:
涉及知識(shí)點(diǎn)
- scroll-view?可滾動(dòng)視圖區(qū)域。使用豎向滾動(dòng)時(shí),需要給<scroll-view>一個(gè)固定高度,通過(guò) WXSS 設(shè)置 height。組件屬性的長(zhǎng)度單位默認(rèn)為px,2.4.0起支持傳入單位(rpx/px)。
- scroll-y? 是否允許縱向滾動(dòng),默認(rèn)false。
- scroll-into-view? 值應(yīng)為某子元素id(id不能以數(shù)字開(kāi)頭)。設(shè)置哪個(gè)方向可滾動(dòng),則在哪個(gè)方向滾動(dòng)到該元素(動(dòng)態(tài)更新該屬性的值,實(shí)現(xiàn)左右聯(lián)動(dòng))。
- view 基礎(chǔ)控件。
- hover-class? ?設(shè)置指定按下去的樣式類。當(dāng) hover-class="none" 時(shí),沒(méi)有點(diǎn)擊態(tài)效果。
- wx:for 在組件上使用 wx:for 控制屬性綁定一個(gè)數(shù)組,即可使用數(shù)組中各項(xiàng)的數(shù)據(jù)重復(fù)渲染該組件。默認(rèn)數(shù)組的當(dāng)前項(xiàng)的下標(biāo)變量名默認(rèn)為 index,數(shù)組當(dāng)前項(xiàng)的變量名默認(rèn)為 item。
- bindtap='showItem' 綁定組件的單擊事件,不加括弧。
示例效果圖
示例效果圖如下所示:
核心代碼
WXML代碼如下:
1 <!--pages/show/show.wxml--> 2 <view class="show-info"> 3 <scroll-view class='left' scroll-y> 4 <view class="jy-item" wx:for="{{jytype}}" wx:key="id" hover-class="jy-item-hover" wx:for-item="item" bindtap='showItem' data-id="{{item.id}}"> 5 <image src="{{item.url}}"></image> 6 <label>{{item.name}}</label> 7 </view> 8 </scroll-view> 9 <scroll-view class='right' scroll-y scroll-into-view="{{viewId}}"> 10 <view class="jy-detail" wx:for="{{jydetail}}" wx:key="id" id= "D-{{detail.typeid}}-{{detail.id}}" wx:for-item="detail" bindtap='showDetail' data-id="{{detail.id}}"> 11 <image src="{{detail.url}}"></image> 12 <label>{{detail.name}}</label> 13 </view> 14 </scroll-view> 15 </view>
JS代碼如下:
1 showItem: function(event) { 2 var that=this; 3 var viewId = "D-" + event.currentTarget.dataset.id + "-" + event.currentTarget.dataset.id+"00"; 4 that.setData({ 5 viewId: viewId 6 }); 7 console.log(viewId); 8 },
WXSS布局如下,此處主要用到了盒子布局(display: flex;flex-direction: row;):
1 .show-info { 2 height: 100%; 3 display: flex; 4 flex-direction: row; 5 align-items: flex-start; 6 padding: 10rpx 0; 7 box-sizing: border-box; 8 } 9 10 .left { 11 width: 30%; 12 height: 100%; 13 display: flex; 14 flex-direction: column; 15 margin:2px; 16 } 17 18 .jy-item-hover{ 19 border: none; 20 } 21 22 .right { 23 width: 70%; 24 height: 1200rpx; 25 display: flex; 26 flex-direction: column; 27 margin: 2px; 28 }
備注
學(xué)而時(shí)習(xí)之,不亦說(shuō)乎。