vue通讯录按名子首字母排序分组代码实现
时间: 2023-07-26 18:47:39 浏览: 317
以下是一个完整的 Vue 组件代码实现:
```html
<template>
<div>
<div v-for="(contacts, letter) in groupedContacts" :key="letter">
<h2>{{ letter }}</h2>
<ul>
<li v-for="contact in contacts" :key="contact.phone">{{ contact.name }}</li>
</ul>
</div>
</div>
</template>
<script>
import pinyin from 'pinyin';
export default {
data() {
return {
contacts: [
{ name: '张三', phone: '123456789' },
{ name: '李四', phone: '987654321' },
{ name: '王五', phone: '111111111' },
{ name: '赵六', phone: '222222222' },
{ name: '钱七', phone: '333333333' },
{ name: '孙八', phone: '444444444' },
{ name: '周九', phone: '555555555' },
{ name: '吴十', phone: '666666666' },
],
groupedContacts: {},
};
},
mounted() {
const pinyinContacts = this.contacts.map(contact => {
const pinyinName = pinyin(contact.name, { style: pinyin.STYLE_FIRST_LETTER }).join('');
return { ...contact, pinyinName };
});
const groupedContacts = pinyinContacts.reduce((groups, contact) => {
const firstLetter = contact.pinyinName[0].toUpperCase();
if (!groups[firstLetter]) {
groups[firstLetter] = [];
}
groups[firstLetter].push(contact);
return groups;
}, {});
Object.keys(groupedContacts).forEach(key => {
groupedContacts[key].sort((a, b) => a.name.localeCompare(b.name));
});
this.groupedContacts = groupedContacts;
},
};
</script>
```
在这个示例中,我们使用了 pinyin 库将联系人名字转换为拼音,然后根据拼音首字母进行分组和排序,并最终在页面上渲染出分组后的通讯录。
阅读全文