vue实现添加删除
Vue 实现添加和删除功能
在 Vue 中实现添加和删除功能通常涉及数据绑定、事件处理和列表渲染。以下是实现的基本方法。
添加功能
-
定义数据 在 Vue 的
data中定义一个数组来存储需要渲染的列表项。data() { return { items: [], newItem: '' } } -
绑定输入框 使用
v-model绑定输入框的值到newItem,用于获取用户输入。<input v-model="newItem" placeholder="输入新项"> -
添加方法 在
methods中定义添加方法,将newItem添加到items数组中,并清空输入框。methods: { addItem() { if (this.newItem.trim() !== '') { this.items.push(this.newItem); this.newItem = ''; } } } -
触发添加 通过按钮或回车键触发添加方法。

<button @click="addItem">添加</button>
删除功能
-
渲染列表 使用
v-for渲染列表,并为每个项添加删除按钮。<ul> <li v-for="(item, index) in items" :key="index"> {{ item }} <button @click="removeItem(index)">删除</button> </li> </ul> -
删除方法 在
methods中定义删除方法,通过索引从items数组中移除对应项。methods: { removeItem(index) { this.items.splice(index, 1); } }
完整示例
<template>
<div>
<input v-model="newItem" placeholder="输入新项" @keyup.enter="addItem">
<button @click="addItem">添加</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item }}
<button @click="removeItem(index)">删除</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
newItem: ''
}
},
methods: {
addItem() {
if (this.newItem.trim() !== '') {
this.items.push(this.newItem);
this.newItem = '';
}
},
removeItem(index) {
this.items.splice(index, 1);
}
}
}
</script>
使用 Vuex 管理状态
如果项目规模较大,可以使用 Vuex 集中管理状态。

-
定义 Vuex Store 在 store 中定义状态和 mutations。
const store = new Vuex.Store({ state: { items: [] }, mutations: { ADD_ITEM(state, item) { state.items.push(item); }, REMOVE_ITEM(state, index) { state.items.splice(index, 1); } } }); -
组件中调用 mutations 在组件中使用
mapMutations或直接调用commit。methods: { ...mapMutations(['ADD_ITEM', 'REMOVE_ITEM']), addItem() { if (this.newItem.trim() !== '') { this.ADD_ITEM(this.newItem); this.newItem = ''; } }, removeItem(index) { this.REMOVE_ITEM(index); } }
使用计算属性优化
如果需要基于列表项进行复杂操作,可以使用计算属性。
computed: {
filteredItems() {
return this.items.filter(item => item.includes('特定条件'));
}
}
以上方法可以根据实际需求进行调整和扩展。






