vue增删改查简单实现
Vue 增删改查简单实现
以下是一个基于 Vue 3 的简单增删改查(CRUD)实现示例,使用 Vue 的 Composition API 和响应式数据管理。

初始化项目
确保已安装 Vue 3 环境。可以通过以下命令创建一个新项目:

npm init vue@latest vue-crud-demo
cd vue-crud-demo
npm install
核心代码实现
在 src/App.vue 中编写以下代码:
<template>
<div>
<h3>用户列表</h3>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>
<button @click="editUser(user)">编辑</button>
<button @click="deleteUser(user.id)">删除</button>
</td>
</tr>
</tbody>
</table>
<h3>{{ editing ? '编辑用户' : '添加用户' }}</h3>
<input v-model="currentUser.name" placeholder="请输入姓名" />
<button @click="saveUser">{{ editing ? '更新' : '添加' }}</button>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue';
const users = reactive([
{ id: 1, name: '张三' },
{ id: 2, name: '李四' }
]);
const currentUser = reactive({
id: null,
name: ''
});
const editing = ref(false);
const saveUser = () => {
if (editing.value) {
const index = users.findIndex(u => u.id === currentUser.id);
if (index !== -1) {
users[index].name = currentUser.name;
}
} else {
const newId = users.length > 0 ? Math.max(...users.map(u => u.id)) + 1 : 1;
users.push({ id: newId, name: currentUser.name });
}
resetForm();
};
const editUser = (user) => {
currentUser.id = user.id;
currentUser.name = user.name;
editing.value = true;
};
const deleteUser = (id) => {
const index = users.findIndex(u => u.id === id);
if (index !== -1) {
users.splice(index, 1);
}
};
const resetForm = () => {
currentUser.id = null;
currentUser.name = '';
editing.value = false;
};
</script>
关键点说明
- 数据管理:使用
reactive创建响应式对象users和currentUser,ref管理编辑状态。 - 添加功能:通过
saveUser方法判断当前是编辑还是添加,动态生成新 ID 并更新数组。 - 编辑功能:
editUser方法将选中用户数据填充到表单,标记为编辑状态。 - 删除功能:通过
splice从数组中移除指定 ID 的用户。
样式优化
可添加基础样式提升交互体验:
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
button {
margin: 0 5px;
cursor: pointer;
}
扩展建议
- 添加表单验证(如空值检查)。
- 使用组件拆分逻辑(如单独的表单组件、列表组件)。
- 集成后端 API(通过
axios发送请求)。 - 加入状态管理(如 Pinia)处理复杂数据流。






