vue实现crud功能
Vue实现CRUD功能
安装Vue及相关依赖
确保已安装Vue CLI,通过以下命令创建项目:
npm install -g @vue/cli
vue create vue-crud-demo
cd vue-crud-demo
安装axios用于HTTP请求:
npm install axios
创建数据模型
在src目录下创建data.js,模拟后端数据:
export const items = [
{ id: 1, name: 'Item 1', description: 'Description 1' },
{ id: 2, name: 'Item 2', description: 'Description 2' }
];
实现CRUD组件
创建CrudComponent.vue文件:
<template>
<div>
<h3>Item List</h3>
<table>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.description }}</td>
<td>
<button @click="editItem(item)">Edit</button>
<button @click="deleteItem(item.id)">Delete</button>
</td>
</tr>
</table>
<h3>{{ editing ? 'Edit Item' : 'Add Item' }}</h3>
<input v-model="currentItem.name" placeholder="Name">
<input v-model="currentItem.description" placeholder="Description">
<button @click="saveItem">{{ editing ? 'Update' : 'Save' }}</button>
</div>
</template>
<script>
import { items } from '../data';
export default {
data() {
return {
items: [...items],
currentItem: { id: null, name: '', description: '' },
editing: false
};
},
methods: {
saveItem() {
if (this.editing) {
const index = this.items.findIndex(i => i.id === this.currentItem.id);
this.items.splice(index, 1, { ...this.currentItem });
} else {
this.currentItem.id = Math.max(...this.items.map(i => i.id)) + 1;
this.items.push({ ...this.currentItem });
}
this.resetForm();
},
editItem(item) {
this.currentItem = { ...item };
this.editing = true;
},
deleteItem(id) {
this.items = this.items.filter(item => item.id !== id);
},
resetForm() {
this.currentItem = { id: null, name: '', description: '' };
this.editing = false;
}
}
};
</script>
集成到主应用
修改App.vue:
<template>
<div id="app">
<CrudComponent />
</div>
</template>
<script>
import CrudComponent from './components/CrudComponent.vue';
export default {
components: { CrudComponent }
};
</script>
运行项目
启动开发服务器:
npm run serve
连接真实后端(可选)
替换CrudComponent.vue中的方法为API调用:

methods: {
async fetchItems() {
const response = await axios.get('/api/items');
this.items = response.data;
},
async saveItem() {
if (this.editing) {
await axios.put(`/api/items/${this.currentItem.id}`, this.currentItem);
} else {
await axios.post('/api/items', this.currentItem);
}
this.fetchItems();
this.resetForm();
},
async deleteItem(id) {
await axios.delete(`/api/items/${id}`);
this.fetchItems();
}
},
created() {
this.fetchItems();
}
关键点说明
- 使用
v-model实现表单双向绑定 - 通过条件渲染区分创建和编辑模式
- 数组方法如
filter、findIndex处理数据操作 - 对象展开运算符
...保持数据不可变性
以上实现可根据实际需求扩展验证、分页等功能。






