vue怎么实现通讯录
Vue实现通讯录的方法
数据结构和状态管理
通讯录通常需要管理联系人列表,可以使用Vue的data或Vuex/Pinia进行状态管理。基础数据结构示例:
data() {
return {
contacts: [
{ id: 1, name: '张三', phone: '13800138000', group: '家人' },
{ id: 2, name: '李四', phone: '13900139000', group: '同事' }
],
newContact: { name: '', phone: '', group: '' },
searchQuery: ''
}
}
列表渲染和搜索功能
使用v-for渲染联系人列表,结合计算属性实现搜索过滤:
computed: {
filteredContacts() {
return this.contacts.filter(contact =>
contact.name.includes(this.searchQuery) ||
contact.phone.includes(this.searchQuery)
)
}
}
模板部分:
<input v-model="searchQuery" placeholder="搜索联系人">
<ul>
<li v-for="contact in filteredContacts" :key="contact.id">
{{ contact.name }} - {{ contact.phone }}
</li>
</ul>
分组显示
按分组归类显示联系人,可使用reduce处理数据:
computed: {
groupedContacts() {
return this.contacts.reduce((groups, contact) => {
const group = contact.group || '未分组'
groups[group] = groups[group] || []
groups[group].push(contact)
return groups
}, {})
}
}
模板示例:
<div v-for="(groupContacts, groupName) in groupedContacts" :key="groupName">
<h3>{{ groupName }}</h3>
<ul>
<li v-for="contact in groupContacts" :key="contact.id">
{{ contact.name }} - {{ contact.phone }}
</li>
</ul>
</div>
字母索引导航
实现右侧字母快速导航需要:
- 提取所有分组首字母
- 监听点击事件滚动到对应分组
计算首字母列表:
computed: {
groupLetters() {
return Object.keys(this.groupedContacts)
.map(group => group.charAt(0).toUpperCase())
.filter((v, i, a) => a.indexOf(v) === i)
.sort()
}
}
完整组件示例
<template>
<div class="address-book">
<input v-model="searchQuery" placeholder="搜索联系人">
<div class="index-bar">
<span
v-for="letter in groupLetters"
:key="letter"
@click="scrollToGroup(letter)"
>
{{ letter }}
</span>
</div>
<div
v-for="(groupContacts, groupName) in filteredGroups"
:key="groupName"
:ref="'group-'+groupName"
>
<h3>{{ groupName }}</h3>
<ul>
<li v-for="contact in groupContacts" :key="contact.id">
{{ contact.name }} - {{ contact.phone }}
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
contacts: [...],
searchQuery: ''
}
},
computed: {
filteredGroups() {
// 实现搜索过滤后的分组逻辑
},
groupLetters() {
// 返回首字母列表
}
},
methods: {
scrollToGroup(letter) {
const group = this.$refs['group-'+letter]?.[0]
group?.scrollIntoView({ behavior: 'smooth' })
}
}
}
</script>
进阶优化方向
- 使用Web Workers处理大量联系人数据的搜索和分组
- 添加虚拟滚动优化长列表性能
- 集成IndexedDB进行本地数据持久化
- 实现联系人编辑和删除功能
- 添加拼音库支持中文拼音搜索
实现通讯录核心在于合理组织数据结构,利用Vue的响应式特性和计算属性高效处理数据展示逻辑。根据项目复杂度可选择本地状态管理或引入Vuex/Pinia。







