基于uniapp与uview做一个按拼音首字母排序的通讯录页面
效果图:
第一步导入pinyin库并应用,用于区分汉字的拼音首字母
npm i pinyin
import pinyin from "pinyin"
完整算法:
function getListByPinyinFirstLetter(data) {const newList = {};for (const item of data) {let firstLetter;if (/[a-zA-Z]/.test(item.name.charAt(0))) {// 如果是英文字母开头的直接使用大写首字母firstLetter = item.name.charAt(0).toUpperCase();} else {const pinyinArray = pinyin(item.name, {style: pinyin.STYLE_FIRST_LETTER, // 提取拼音首字母});if (pinyinArray.length > 0) {firstLetter = /[a-zA-Z]/.test(pinyinArray[0][0].toUpperCase()) ? pinyinArray[0][0].toUpperCase() :"#"; // 获取拼音首字母并转换为大写} else {// 如果没有拼音首字母,则归类为#firstLetter = "#";}}if (!newList[firstLetter]) {newList[firstLetter] = [];}newList[firstLetter].push(item);}// 将键按字母顺序排序const sortedKeys = Object.keys(newList).sort((a, b) => {if (a === '#') return 1;if (b === '#') return -1;return a.localeCompare(b);});const sortedNewList = {};for (const key of sortedKeys) {sortedNewList[key] = newList[key];}console.log(sortedNewList, sortedKeys);indexList.value = sortedKeyslist.value = sortedNewList;}
完整代码(样式自己定义):
<template>{{newList}}<u-index-list :scrollTop="scrollTop" v-if="indexList.length"><view v-for="(item, index) in indexList" :key="index"><u-index-anchor :index="item" /><view class="list-cell" v-for="(item,index) in list[item]">{{item.name}}</view></view></u-index-list>
</template><script setup>import {ref,} from "vue";import pinyin from "pinyin"import {onLoad,onPageScroll} from "@dcloudio/uni-app"onLoad(() => {getListByPinyinFirstLetter(testList.value)})const indexList = ref([])const testList = ref([{name: "张三"},{name: "张学友"},{name: "asasd"},{name: "大师"},{name: "(字符"},])const list = ref([])function getListByPinyinFirstLetter(data) {const newList = {};for (const item of data) {let firstLetter;if (/[a-zA-Z]/.test(item.name.charAt(0))) {// 如果是英文字母开头的直接使用大写首字母firstLetter = item.name.charAt(0).toUpperCase();} else {const pinyinArray = pinyin(item.name, {style: pinyin.STYLE_FIRST_LETTER, // 提取拼音首字母});if (pinyinArray.length > 0) {firstLetter = /[a-zA-Z]/.test(pinyinArray[0][0].toUpperCase()) ? pinyinArray[0][0].toUpperCase() :"#"; // 获取拼音首字母并转换为大写} else {// 如果没有拼音首字母,则归类为#firstLetter = "#";}}if (!newList[firstLetter]) {newList[firstLetter] = [];}newList[firstLetter].push(item);}// 将键按字母顺序排序const sortedKeys = Object.keys(newList).sort((a, b) => {if (a === '#') return 1;if (b === '#') return -1;return a.localeCompare(b);});const sortedNewList = {};for (const key of sortedKeys) {sortedNewList[key] = newList[key];}console.log(sortedNewList, sortedKeys);indexList.value = sortedKeyslist.value = sortedNewList;}onPageScroll(e => {this.scrollTop = e.scrollTop;})
</script><style lang="scss" scoped>.list-cell {display: flex;box-sizing: border-box;width: 100%;padding: 10px 24rpx;overflow: hidden;color: #323233;font-size: 14px;line-height: 24px;background-color: #fff;}
</style>