Vant IndexBar 在小程序中的简单使用_Vant IndexBar

先看下最终效果图,主要是渲染一个A - Z 的 通讯录。同样的,如果你要做的是城市列表,也可以参考一下。

Vant IndexBar 在小程序中的简单使用_Vant IndexBar _02

 

这边是 Vant IndexBar 官方文档 方便你查阅。

之前的通讯录只是一个列表,名字没有顺序,查找起来不太方便,正好看到Vant组件库里有IndexBar这个组件,所以就立马换掉了,总的来说有以下两个步骤。

1. 格式化数据

一开始,后台给我的数据是这样的,而我只想要一个包含名字的列表就够了。

[  {    "createdAt": "2020-08-27 18:06:53",    "department": "总经理办公室",    "employeeName": "安琪拉",    "objectId": "4a3eed5344",    "phoneNumber": "18012251502",    "serialNumber": "1",    "staffPosition": "总经理",    "updatedAt": "2020-08-27 18:06:53",    "username": "18012251502"  },  {    "createdAt": "2020-08-27 18:06:53",    "department": "生产部",    "employeeName": "吕布",    "objectId": "7236fed315",    "phoneNumber": "18257122100",    "serialNumber": "41",    "staffPosition": "装配",    "updatedAt": "2020-08-27 18:06:53",    "username": "18257122100"  },  {    "createdAt": "2020-08-27 18:06:53",    "department": "技术部",    "employeeName": "赵云",    "objectId": "6a1daa9a80",    "phoneNumber": "15852855556",    "serialNumber": "42",    "staffPosition": "管理员",    "updatedAt": "2020-08-27 18:07:26",    "username": "15852855556"  }]

所以要先把返回的员工列表employeeList做下处理

    let employeeNameList = [];    for (let k in employeeList) {        employeeNameList.push(employeeList[k].employeeName)    }

处理之后的员工姓名表employeeNameList是这样的

[  "安琪拉",  "吕布",  "赵云"]

因为人名是汉字,无法与' A ' , ' B ' .....' X ' , ' Y ' , ' Z ' 匹配,所以需要用第三方库将汉字转换成拼音,再提取首字母去完成匹配。我这边用的是 wl-pinyin 这个库。使用之前先导入一下

import pinyin from "wl-pinyin"

定义一个字母表数组AlphabetList,存放26个大写字母。

AlphabetList : ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"]

拼接数据

      let firstName = {};      this.data.AlphabetList.forEach((item) => {        firstName[item] = [];        employeeNameList.forEach((el) => {          /** 主要在这一句,el代表每个名字如 “安琪拉” ,            pinyin.getFirstLetter(el) 取的是名字的首字母 “AQL” ,            .substring(0, 1) 就是只取第一个字符 ‘A’ **/          let first = pinyin.getFirstLetter(el).substring(0, 1);          if (first == item) {            firstName[item].push(el)          }        })      })

最后得到的数据格式是这样的

{  "A": [    "安琪拉"  ],  "B": [    "百里守约","白起","不知火舞"  ],  ...  "H": [    "黄忠"  ],  "L": [    "吕布"  ],  "M": [      "马可波罗","马超"  ],  ...  "Z": [    "赵云","甄姬"  ]}

2. 布局中引入组件

<van-index-bar :sticky="false" >    <view wx:for="{{employeeNameList}}" wx:for-index="key"  wx:for-item="value">       <!--显示 A-Z -->        <van-index-anchor :use-slot="true" index='{{key}}'>          </van-index-anchor>           <!--遍历每个字母对应的名字数组-->       <view  wx:for='{{value}}' wx:for-item='employeeName' >{{employeeName}}</view>    </view></van-index-bar>

现在是2020年09月19日02:55:02,晚安

Vant IndexBar 在小程序中的简单使用_Vant IndexBar _03