vue如何实现增删
Vue 实现增加功能
通过 v-model 绑定输入框数据,结合数组的 push 方法实现新增。示例代码:
<template>
<input v-model="newItem" placeholder="输入新增内容">
<button @click="addItem">新增</button>
<ul>
<li v-for="(item, index) in items" :key="index">{{ item }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
newItem: '',
items: ['默认项1', '默认项2']
}
},
methods: {
addItem() {
if (this.newItem.trim()) {
this.items.push(this.newItem.trim())
this.newItem = ''
}
}
}
}
</script>
Vue 实现删除功能
使用数组的 splice 方法或 filter 方法移除指定项。示例代码:
<template>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="deleteItem(index)">删除</button>
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['项目A', '项目B', '项目C']
}
},
methods: {
deleteItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
结合增删的完整示例
<template>
<div>
<input v-model="newTodo" @keyup.enter="addTodo">
<button @click="addTodo">添加</button>
<ul>
<li v-for="(todo, index) in todos" :key="index">
{{ todo }}
<button @click="removeTodo(index)">×</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
newTodo: '',
todos: ['学习Vue', '写代码']
}
},
methods: {
addTodo() {
if (this.newTodo.trim()) {
this.todos.push(this.newTodo.trim())
this.newTodo = ''
}
},
removeTodo(index) {
this.todos.splice(index, 1)
}
}
}
</script>
使用 Vuex 管理状态
对于大型应用建议使用状态管理:

// store.js
const store = new Vuex.Store({
state: {
items: []
},
mutations: {
ADD_ITEM(state, payload) {
state.items.push(payload)
},
DELETE_ITEM(state, index) {
state.items.splice(index, 1)
}
}
})
// 组件内调用
methods: {
addItem() {
this.$store.commit('ADD_ITEM', this.newItem)
},
deleteItem(index) {
this.$store.commit('DELETE_ITEM', index)
}
}
关键注意事项
- 列表渲染必须设置
:key属性 - 删除操作建议使用唯一ID而非索引作为标识
- 对于复杂数据结构,建议使用深拷贝处理数据变更
- 表单输入需添加非空校验和trim处理






