vue前端实现增删改
使用 Vue 实现增删改功能
数据绑定与列表渲染
通过 v-model 实现表单数据双向绑定,结合 v-for 渲染列表。示例代码:
<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>
添加功能实现
初始化数据并定义添加方法:

<script>
export default {
data() {
return {
items: [],
newItem: { name: '' }
}
},
methods: {
addItem() {
if (this.newItem.name.trim()) {
this.items.push({...this.newItem});
this.newItem.name = '';
}
}
}
}
</script>
删除功能实现
通过数组的 splice 方法删除指定索引项:

methods: {
deleteItem(index) {
this.items.splice(index, 1);
}
}
编辑功能实现
添加编辑状态和更新方法:
<template>
<div v-if="editingIndex === null">
<input v-model="newItem.name">
<button @click="addItem">添加</button>
</div>
<div v-else>
<input v-model="editItemData.name">
<button @click="updateItem">更新</button>
</div>
</template>
<script>
methods: {
editItem(index) {
this.editingIndex = index;
this.editItemData = {...this.items[index]};
},
updateItem() {
this.items.splice(this.editingIndex, 1, {...this.editItemData});
this.cancelEdit();
},
cancelEdit() {
this.editingIndex = null;
this.editItemData = { name: '' };
}
}
</script>
状态管理(可选)
对于复杂场景可使用 Vuex:
// store.js
const store = new Vuex.Store({
state: {
items: []
},
mutations: {
ADD_ITEM(state, item) {
state.items.push(item);
},
DELETE_ITEM(state, index) {
state.items.splice(index, 1);
}
}
});
注意事项
- 始终为
v-for设置唯一的:key - 复杂表单建议使用
Vue.set确保响应式更新 - 大量数据操作时考虑使用计算属性优化性能






