在小程序中,會有一些需求,常常會有一些按字母A-Z排序,寫過一篇關於vue的字母排序,點擊這里查看,今天寫一篇關於小程序字母排序的案例,效果展示如下
寫之前要和后端定義好數據結構字段,這是我定義的這種數據接口,然后和后端溝通,給我返回這樣的結構。
[ { "letter":"A", "data":[ {"id": 56,"Name": "奧特曼玩具" }, ] },{ "letter":"B", "data":[ {"id": 83,"Name": "巴黎水玻璃瓶"}, { "id": 346,"Name": "保溫杯"}, ] },{ "letter":"C", "data":[ {"id": 91, "Name": "茶葉罐"}, {"id": 92, "Name": "炒菜鐵鍋"}, ] },{ "letter":"D", "data":[ {"id": 9,"Name": "打印紙" }, {"id": 10, "Name": "地板磚"}, ] } ]
letter: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"],
2.頁面布局
<view class="category"> <view class='categrory-wrap'> <!-- 右邊字母 --> <view class='list'> <view class='item' catchtap='handleLetters' data-item='{{item}}' wx:for="{{letter}}" wx:key="index"> {{item}} </view> </view> <!-- //左邊 --> <scroll-view scroll-y="true" scroll-with-animation style="height: {{height}}px" scroll-into-view='{{cityListId}}'> <view class='area-wrap'> <block wx:for='{{cities}}' wx:for-item='letterItem' wx:key='index'> <view class='area'> <view class="title" id='{{letterItem.letter}}'>{{letterItem.letter}}</view> <view class='item-list'> <view class='item' catchtap='handleLetter' wx:for='{{letterItem.data}}' wx:key="index" data-index='{{index}}' data-val='{{item.name}}'>{{item.name}}</view> </view> </view> </block> </view> </scroll-view> </view> </view>
2.1右邊字母這個直接從data定義的字段,然后通過wx:for循環遍歷拿到,展示到頁面效果就行。
2.2左邊內容展示區域,主要利用小程序提供的scroll-view和scroll-info-view
scroll-view:視圖滾動
scroll-info-view:綁定了一個值,通過handleLetters點擊事件實現錨點,相當於a標簽中的#,點擊跳轉對應的位置,首先需要在data定義一個字段cityListId
<view class="title" id='{{letterItem.letter}}'>{{letterItem.letter}}</view>
通過handleLetters點擊跳轉到對應的id位置,這個是循環遍歷的時候獲取到的字母,通過scroll-into-view='{{cityListId}}',與 id='{{letterItem.letter}}' 匹配是那個錨點,跳轉。scroll-with-animation一個動畫延遲的效果
handleLetters(e) { const Item = e.currentTarget.dataset.item; this.setData({ cityListId: Item }); },
2.3循環遍歷,第一次循環遍歷,在這是拿到每個字母展示。注意wx:for遍歷的時候,需要綁定一個key值
<view class="title" id='{{letterItem.letter}}'>{{letterItem.letter}}</view>
再次遍歷是拿到data里面每個字母對應的值。
<view class='item' catchtap='handleLetter' wx:for='{{letterItem.data}}' wx:key="index" data-index='{{index}}' data-val='{{item.name}}'>{{item.name}}</view>
2.4高度是通過小程序提供的一個api來計算出小城市高度賦值,也是需要在data定義好一個height字段
wx.getSystemInfo({ success: function(res) { // 計算主體部分高度,單位為px that.setData({ height: res.windowHeight }) } })
寫到最后,提供一個關於城市列表的數據接口,是自己已經整理好的,拿來直接可以用的,和我定義小程序的字段一模一樣的點擊這里