微信小程式例項:實現tabs選項卡效果
阿新 • • 發佈:2018-12-29
最近微信應用號是炒的如火如荼,熱門滿滿,但是也可以發現搜尋關鍵詞出來,各類網站出現的還都是微信的官方文件解釋。正好趕上這個熱潮,這幾天先把小程式技術文件看了個遍,就直接著手寫案例了。很多元件微信內部已經封裝完了,正好發現沒有tab選項卡效果,這兩天正好研究了下。思路如下:
1、首先點選導航的時候需要兩個變數,一個儲存當前點選樣式類,一個是其它導航預設的樣式類
2、選項卡內容列表同樣也需要兩個變數,一個儲存當前顯示塊,一個儲存的是其它隱藏的預設塊
3、使用三目運算通過點選獲取導航索引,根據索引判斷是否添加當前類【備註,這裡我將點選事件繫結在父級導航欄,通過target物件得到點選觸發的事件物件屬性】
請結合如下效果圖:
接下來直接檢視原始碼:
demo.wxml:
<view class="tab"> <view class="tab-left" bindtap="tabFun"> <view class="{{tabArr.curHdIndex=='0'? 'active' : ''}}" id="tab-hd01" data-id="0">tab-hd01</view> <view class="{{tabArr.curHdIndex=='1'? 'active' : ''}}" id="tab-hd02" data-id="1">tab-hd01</view> <view class="{{tabArr.curHdIndex=='2'? 'active' : ''}}" id="tab-hd03" data-id="2">tab-hd01</view> <view class="{{tabArr.curHdIndex=='3'? 'active' : ''}}" id="tab-hd04" data-id="3">tab-hd01</view> </view> <view class="tab-right"> <view class="right-item {{tabArr.curBdIndex=='0'? 'active' : ''}}">tab-bd01</view> <view class="right-item {{tabArr.curBdIndex=='1'? 'active' : ''}}">tab-bd02</view> <view class="right-item {{tabArr.curBdIndex=='2'? 'active' : ''}}">tab-bd03</view> <view class="right-item {{tabArr.curBdIndex=='3'? 'active' : ''}}">tab-bd04</view> </view> </view>
demo.js:
Page( { data: { tabArr: { curHdIndex: 0, curBdIndex: 0 }, }, tabFun: function(e){ //獲取觸發事件元件的dataset屬性 var _datasetId=e.target.dataset.id; console.log("----"+_datasetId+"----"); var _obj={}; _obj.curHdIndex=_datasetId; _obj.curBdIndex=_datasetId; this.setData({ tabArr: _obj }); }, onLoad: function( options ) { alert( "------" ); } });
demo.wxss:
.tab{
display: flex;
flex-direction: row;
}
.tab-left{
width: 200rpx;
line-height: 160%;
border-right: solid 1px gray;
}
.tab-left view{
border-bottom: solid 1px red;
}
.tab-left .active{
color: #f00;
}
.tab-right{
line-height: 160%;
}
.tab-right .right-item{
padding-left: 15rpx;
display: none;
}
.tab-right .right-item.active{
display: block;
}
最終演示效果如下:
以上僅是個人方案,如果有更好的方案,歡迎提出~