城市列表侧边栏首字母js-pinyin插件使用及实例

1,005 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

需求:

平时做项目,会遇到一些关于地址的选择之列的,大量的地址列表信息(如高铁站、机场站、地理位置),需要右侧有个索引栏能起到筛选和分类的作用。在移动端我们一般采用vant-ui中的IndexBar, IndexAnchor和js-pinyin包来实现。

1.安装:

npm install js-pinyin

2.使用:

配合vant-ui中的IndexBar, IndexAnchor使用 安装完成后在需要使用的页面引入插件:

import pinyin from "js-pinyin";

调用接口后获取地区列表数据,对每一条数据进行遍历,调用pinyin.getCamelChars()方法对每个城市的首字母进行转化,得到一个首字母组成的列表

          i.acronym = pinyin
            .getCamelChars(i.airportName)
            .substr(0, 1)
            .toLocaleUpperCase();
          charList.push(i.acronym);
          return i;
        });
        airCharList = Array.from(new Set(charList)).sort();

将首字母组成的这个列表数据赋值给van-index-bar的indexList

        :index-list="airCharList"
        :sticky-offset-top="stickyOffsetTop"
      >
        <view v-for="item in airTrainList" :key="item.acr">
          <van-index-anchor :index="item.acr" />
          <view
            class="city-item"
            v-for="(air, index) in item.list"
            :key="index"
            @click="checkAirTrain(air)"
            >{{ air.airportName }}</view
          >
        </view>
      </van-index-bar>

同时也要对原有的列表数据进行调整,使其列表排列顺序与字符排列顺序一致,即按照首字母"A,B,C,D..."这样的顺序排列

        charList.forEach((char) => {
          let obj = {};
          let list = [];
          arrList.forEach((i) => {
            if (char == i.acronym) {
              list.push(i);
            }
          });
          obj.acr = char;
          obj.list = list;
          airAllList.push(obj);
        });
        this.airTrainList = airAllList;
        this.airCharList = charList;

js-pinyin方法扩展:

console.log(pinyin.getFullChars('管理员')) //GuanLiYuan; console.log(pinyin.getCamelChars('管理员')) //GLY; console.log(pinyin.getCamelChars('1234')) //1234; console.log(pinyin.getCamelChars('管')) //G;