vue实现通讯录代码
Vue 实现通讯录代码
通讯录功能通常包括联系人列表展示、搜索、添加/删除联系人等操作。以下是一个基于 Vue 3 的通讯录实现示例,包含核心功能模块和代码片段。
数据结构设计
通讯录的核心是联系人数据,通常用数组存储,每个联系人包含姓名、电话等字段:
const contacts = ref([
{ id: 1, name: '张三', phone: '13800138000' },
{ id: 2, name: '李四', phone: '13900139000' }
]);
列表渲染
使用 v-for 渲染联系人列表,并通过计算属性实现排序(按姓名拼音首字母):

<template>
<div v-for="contact in sortedContacts" :key="contact.id">
{{ contact.name }} - {{ contact.phone }}
</div>
</template>
<script setup>
const sortedContacts = computed(() => {
return [...contacts.value].sort((a, b) =>
a.name.localeCompare(b.name, 'zh-Hans-CN')
);
});
</script>
搜索功能
通过计算属性实现实时搜索过滤:
const searchQuery = ref('');
const filteredContacts = computed(() => {
return sortedContacts.value.filter(contact =>
contact.name.includes(searchQuery.value) ||
contact.phone.includes(searchQuery.value)
);
});
添加联系人
表单绑定实现新增功能:

<template>
<input v-model="newName" placeholder="姓名">
<input v-model="newPhone" placeholder="电话">
<button @click="addContact">添加</button>
</template>
<script setup>
const newName = ref('');
const newPhone = ref('');
const addContact = () => {
contacts.value.push({
id: Date.now(),
name: newName.value,
phone: newPhone.value
});
newName.value = '';
newPhone.value = '';
};
</script>
字母索引栏
实现按字母快速定位(需引入拼音转换库如 pinyin):
// 获取首字母分组
const groupedContacts = computed(() => {
const groups = {};
sortedContacts.value.forEach(contact => {
const letter = pinyin(contact.name[0], { style: 'FIRST_LETTER' })[0][0].toUpperCase();
groups[letter] = groups[letter] || [];
groups[letter].push(contact);
});
return groups;
});
完整组件示例
整合以上功能的完整组件:
<template>
<div class="address-book">
<input v-model="searchQuery" placeholder="搜索联系人">
<div v-for="(group, letter) in filteredGroups" :key="letter">
<h3>{{ letter }}</h3>
<div v-for="contact in group" :key="contact.id">
{{ contact.name }} - {{ contact.phone }}
<button @click="deleteContact(contact.id)">删除</button>
</div>
</div>
<div class="add-form">
<input v-model="newName" placeholder="姓名">
<input v-model="newPhone" placeholder="电话">
<button @click="addContact">添加</button>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
import pinyin from 'pinyin';
// 数据状态
const contacts = ref(/* 初始数据 */);
const searchQuery = ref('');
const newName = ref('');
const newPhone = ref('');
// 业务逻辑方法
const deleteContact = (id) => {
contacts.value = contacts.value.filter(c => c.id !== id);
};
// 计算属性
const filteredGroups = computed(() => {
/* 实现搜索过滤后的分组逻辑 */
});
</script>
进阶优化
- 数据持久化:使用
localStorage保存联系人数据 - 性能优化:对长列表使用虚拟滚动(如
vue-virtual-scroller) - UI 增强:添加字母快速导航栏、动画过渡效果
以上代码提供了 Vue 实现通讯录的核心功能框架,可根据实际需求扩展更多功能如联系人详情页、编辑功能等。






