Vue 模拟通讯录列表用 js-pinyin 获取汉字首字母,形成字母索引

效果图:

流程 :

  1. 获取数据
  2. 提取首个字的拼音的首个字母
  3. 排序并分组

此功能用到Vant组件的 IndexBar 索引栏

1. 安装

js-pinyin npm地址

npm install js-pinyin --save

 2. 引入及使用

<template>
  <div class="wrap">
    <van-index-bar>
      <div v-for="item in filterData" :key="item.letter">
        <van-index-anchor :index="item.letter"></van-index-anchor>
        <div
          class="content"
          v-for="row in item.list"
          :key="row.id"
          @click="go(row.id)"
        >
          {
   
   { row.name }}
        </div>
      </div>
    </van-index-bar>
  </div>
</template>

<script>
export default {
  name: "test",
  data() {
    return {
      filterData: [], // 处理后的 待渲染数据
       // 模拟数据
      mapData: [
        {
          id: 1,
          name: "万景千言",
        },
        {
          id: 2,
          name: "八里沟11",
        },
        {
          id: 2,
          name: "八里沟1",
        },
        {
          id: 2,
          name: "八里沟",
        },
        {
          id: 17,
          name: "京华园",
        },
        {
          id: 21,
          name: "平原博物馆",
        },
        {
          id: 38,
          name: "金牛湖野生动物王国",
        },
      ],
    };
  },
  created() {
    this.test();
  },
  methods: {
    test() {
      // 安装使用 js-pinyin 插件,获取待处理字段的拼音
      const pinyin = require("js-pinyin");
      this.mapData.map((item) => {
        item.pinyin = pinyin.getFullChars(item.name);
      });

      let provice = {};
      this.mapData.map((item) => {
        const Initials = item.pinyin[0].toUpperCase();
        // 如果对象里有当前字母项则直接 push 一个对象,如果没有则创建一个新的键并赋值;
        if (provice[Initials]) {
          provice[Initials].push(item);
        } else {
          provice[Initials] = [item];
        }
      });
      // 将数据转为数组,并按字母顺利排列
      this.filterData = [];
      for (let key in provice) {
        const obj = { letter: key, list: provice[key] };
        this.filterData.push(obj);
      }
      this.filterData.sort((a, b) => {
        return a.letter.localeCompare(b.letter);
      });
    },
  },
};
</script>

猜你喜欢

转载自blog.csdn.net/m0_67063430/article/details/128951993