小程序索引列表排序

在小程序中,会有一些需求,常常会有一些按字母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": "地板砖"},
    ]
  }
]
1.页面的初始数据
在data定义一个letter字母数组,用于存放数组的,字母是data直接定义好的,然后在页面直接循环遍历就行
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
        })
      }
    })

写到最后,提供一个关于城市列表的数据接口,是自己已经整理好的,拿来直接可以用的,和我定义小程序的字段一模一样的点击这里

posted @ 2019-07-24 15:53  小周sri的码农  阅读(3957)  评论(0编辑  收藏  举报