vue实现CRUD
Vue 实现 CRUD 功能
项目初始化
创建一个 Vue 项目,确保已安装 Vue CLI 或使用 Vite 进行初始化。安装必要的依赖,如 axios 用于 HTTP 请求。
npm create vue@latest my-crud-app
cd my-crud-app
npm install axios
后端 API 准备
假设后端 API 提供以下端点:
GET /api/items:获取所有数据POST /api/items:创建新数据PUT /api/items/:id:更新数据DELETE /api/items/:id:删除数据
组件结构
创建主组件 ItemList.vue,包含表格展示数据和操作按钮。
数据获取与展示
使用 axios 获取数据并在表格中渲染。

<template>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>
<button @click="editItem(item)">Edit</button>
<button @click="deleteItem(item.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
items: []
};
},
mounted() {
this.fetchItems();
},
methods: {
fetchItems() {
axios.get('/api/items')
.then(response => {
this.items = response.data;
})
.catch(error => {
console.error('Error fetching items:', error);
});
}
}
};
</script>
创建数据
添加表单和提交逻辑。
<template>
<div>
<form @submit.prevent="addItem">
<input v-model="newItem.name" placeholder="Item name" required>
<button type="submit">Add</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
newItem: { name: '' }
};
},
methods: {
addItem() {
axios.post('/api/items', this.newItem)
.then(response => {
this.items.push(response.data);
this.newItem.name = '';
})
.catch(error => {
console.error('Error adding item:', error);
});
}
}
};
</script>
更新数据
添加编辑逻辑和模态框。

<template>
<div>
<dialog v-if="editingItem" open>
<form @submit.prevent="updateItem">
<input v-model="editingItem.name" required>
<button type="submit">Save</button>
<button type="button" @click="editingItem = null">Cancel</button>
</form>
</dialog>
</div>
</template>
<script>
export default {
data() {
return {
editingItem: null
};
},
methods: {
editItem(item) {
this.editingItem = { ...item };
},
updateItem() {
axios.put(`/api/items/${this.editingItem.id}`, this.editingItem)
.then(response => {
const index = this.items.findIndex(i => i.id === response.data.id);
this.items.splice(index, 1, response.data);
this.editingItem = null;
})
.catch(error => {
console.error('Error updating item:', error);
});
}
}
};
</script>
删除数据
实现删除功能。
<script>
export default {
methods: {
deleteItem(id) {
if (confirm('Are you sure?')) {
axios.delete(`/api/items/${id}`)
.then(() => {
this.items = this.items.filter(item => item.id !== id);
})
.catch(error => {
console.error('Error deleting item:', error);
});
}
}
}
};
</script>
完整组件整合
将所有功能整合到 ItemList.vue 中,确保数据和方法协同工作。
样式优化
添加基础样式提升用户体验。
<style scoped>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
</style>
注意事项
- 使用
v-model进行表单数据双向绑定。 - 错误处理通过
catch捕获并反馈给用户。 - 编辑时使用对象副本避免直接修改原数据。
通过以上步骤,Vue 实现的 CRUD 功能可以完成数据的展示、创建、更新和删除操作。






