vue里实现增删改查
在 Vue 中实现增删改查(CRUD)
数据绑定与列表渲染
使用 v-for 指令渲染数据列表,结合 v-model 实现表单双向绑定。示例代码:
<template>
<div>
<input v-model="newItem.name" placeholder="名称" />
<button @click="addItem">添加</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }}
<button @click="editItem(index)">编辑</button>
<button @click="deleteItem(index)">删除</button>
</li>
</ul>
</div>
</template>
添加功能
通过数组的 push 方法实现数据添加:

data() {
return {
items: [],
newItem: { name: '' }
}
},
methods: {
addItem() {
if (this.newItem.name.trim()) {
this.items.push({...this.newItem});
this.newItem.name = '';
}
}
}
删除功能
使用 splice 方法根据索引删除数据:

methods: {
deleteItem(index) {
this.items.splice(index, 1);
}
}
编辑功能
通过临时存储编辑状态实现修改:
data() {
return {
editingIndex: -1,
tempItem: {}
}
},
methods: {
editItem(index) {
this.editingIndex = index;
this.tempItem = {...this.items[index]};
},
saveEdit() {
Object.assign(this.items[this.editingIndex], this.tempItem);
this.cancelEdit();
},
cancelEdit() {
this.editingIndex = -1;
}
}
与后端交互
使用 axios 发送 HTTP 请求:
import axios from 'axios';
methods: {
async fetchData() {
const res = await axios.get('/api/items');
this.items = res.data;
},
async saveItem(item) {
await axios.post('/api/items', item);
}
}
完整组件示例
<template>
<div>
<input v-model="tempItem.name" />
<button v-if="editingIndex === -1" @click="addItem">添加</button>
<template v-else>
<button @click="saveEdit">保存</button>
<button @click="cancelEdit">取消</button>
</template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ item.name }}
<button @click="editItem(index)">编辑</button>
<button @click="deleteItem(index)">删除</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
tempItem: { name: '' },
editingIndex: -1
}
},
methods: {
addItem() {
this.items.push({...this.tempItem});
this.tempItem.name = '';
},
editItem(index) {
this.editingIndex = index;
this.tempItem = {...this.items[index]};
},
saveEdit() {
this.items[this.editingIndex] = {...this.tempItem};
this.cancelEdit();
},
deleteItem(index) {
this.items.splice(index, 1);
},
cancelEdit() {
this.editingIndex = -1;
this.tempItem.name = '';
}
}
}
</script>






