索引列表的制作,中文拼音排序

发布时间 2023-04-26 10:43:29作者: 幻影之舞

业务上最近需要做一个选择人员的页面,右侧会有一个快速索引,样式如下:

这个首先要把名字转拼音,然后取首字母,转大写,然后在新建的空对象里进行比对,如果有这个字母,就吧这条数据push进去,没有的话就在对象里创建该首字母的数组,再push进去,这样就形成了一个包含26个英文字母数组的对象

结构就是 

对象名 {
    A: [....],
    B:[....],
    .......
}

最后在进行一下排序就可以了

代码:

<u-index-list :index-list="indexList" :sticky="false">
            <template v-for="(item, index) in userList">
                <u-index-item>
                    <u-index-anchor :text="indexList[index]"></u-index-anchor>
                    <u-cell-group>
                        <u-checkbox-group borderBottom v-model="checkboxValue"  placement="column"  shape="circle">
                            <u-checkbox  v-for="(user) in item.list"  :key="user.userId" :label="user.userName" :name="user.userName" @change="checkboxChange(user)">
                            </u-checkbox>    
                        </u-checkbox-group>
                    </u-cell-group>
                </u-index-item>
            </template>
        </u-index-list>

用的是uview的索引列表组件, pinyin是用的js-pinyin ,要npm装一下就可以了

npm install js-pinyin

然后使用的页面引入一下,可以把汉字转为拼音

import pinyin from 'js-pinyin'
data(){
return{ indexList: ['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', '#' ], userList: [], checkboxValue: [], } }, methods: { setUserList(val) { val.map((item) => { item.pinyin = pinyin.getFullChars(item.userName); }); let provice = {}; val.map((item) => { const Initials = item.pinyin[0].toUpperCase(); // 如果对象里有当前字母项则直接 push 一个对象,如果没有则创建一个新的键并赋值; if (provice[Initials]) { provice[Initials].push(item); } else { provice[Initials] = [item]; } }); // 将数据转为数组,并按字母顺利排列 this.userList = []; for (let key in provice) { const obj = { letter: key, list: provice[key] }; this.userList.push(obj); } this.userList.sort((a, b) => { return a.letter.localeCompare(b.letter); }); }, }

大体逻辑就是这样的

 

 样式什么的没来得及做,忙着对接口,先拿到数据再说,样式后面再慢慢搞吧