vue实现通讯录代码
实现思路
Vue实现通讯录的核心在于数据管理和组件交互。通常需要包含联系人列表、搜索功能、分组索引以及添加/编辑功能。

基本结构
创建Vue组件时需包含以下部分:
- 数据模型:存储联系人数组
- 字母索引栏:实现快速跳转
- 搜索框:过滤联系人
- 列表渲染:展示联系人信息
核心代码示例
数据模型
data() {
return {
contacts: [
{ name: '张三', phone: '13800138000', initial: 'Z' },
{ name: '李四', phone: '13900139000', initial: 'L' }
],
searchText: ''
}
}
计算属性处理数据
computed: {
filteredContacts() {
return this.contacts.filter(item =>
item.name.includes(this.searchText) ||
item.phone.includes(this.searchText)
)
},
groupedContacts() {
const groups = {}
this.filteredContacts.forEach(item => {
const initial = item.initial.toUpperCase()
if (!groups[initial]) {
groups[initial] = []
}
groups[initial].push(item)
})
return groups
},
initials() {
return Object.keys(this.groupedContacts).sort()
}
}
模板部分
<div class="address-book">
<input v-model="searchText" placeholder="搜索联系人">
<div class="index-bar">
<span
v-for="initial in initials"
:key="initial"
@click="scrollTo(initial)"
>
{{ initial }}
</span>
</div>
<div class="contact-list">
<div v-for="(group, initial) in groupedContacts" :key="initial">
<h3 :id="initial">{{ initial }}</h3>
<div
v-for="contact in group"
:key="contact.phone"
class="contact-item"
>
<span>{{ contact.name }}</span>
<span>{{ contact.phone }}</span>
</div>
</div>
</div>
</div>
滚动定位方法
methods: {
scrollTo(initial) {
const element = document.getElementById(initial)
if (element) {
element.scrollIntoView({ behavior: 'smooth' })
}
}
}
样式优化建议
.address-book {
position: relative;
height: 100vh;
}
.index-bar {
position: fixed;
right: 10px;
top: 50%;
transform: translateY(-50%);
display: flex;
flex-direction: column;
}
.contact-list {
overflow-y: auto;
height: calc(100% - 60px);
}
.contact-item {
padding: 10px;
border-bottom: 1px solid #eee;
}
功能扩展建议
- 添加本地存储功能保存联系人
- 实现联系人详情页和编辑功能
- 添加手机震动反馈当点击字母索引时
- 优化移动端触摸事件处理
性能优化
对于大型通讯录,建议:
- 使用虚拟滚动技术
- 对列表数据进行分页加载
- 使用Web Worker处理搜索过滤
以上代码提供了Vue实现通讯录的基本框架,可根据实际需求进行调整和扩展。






