vue实现动态添加删除
Vue 动态添加和删除的实现方法
使用 v-for 和数组方法
在 Vue 中可以通过 v-for 指令结合数组方法来动态渲染列表,并通过数组的 push 和 splice 方法实现添加和删除功能。
<template>
<div>
<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: ['项目1', '项目2', '项目3']
}
},
methods: {
addItem() {
this.items.push(`项目${this.items.length + 1}`)
},
removeItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
使用计算属性
对于更复杂的动态内容,可以使用计算属性来管理数据,并通过方法来修改数据源。
<template>
<div>
<input v-model="newItem" placeholder="输入新项目">
<button @click="addItem">添加</button>
<ul>
<li v-for="(item, index) in filteredItems" :key="index">
{{ item }}
<button @click="removeItem(index)">删除</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
newItem: ''
}
},
computed: {
filteredItems() {
return this.items.filter(item => item.length > 0)
}
},
methods: {
addItem() {
if (this.newItem.trim()) {
this.items.push(this.newItem)
this.newItem = ''
}
},
removeItem(index) {
this.items.splice(index, 1)
}
}
}
</script>
动态组件
对于需要动态添加和删除组件的情况,可以使用动态组件配合 is 属性。
<template>
<div>
<button @click="addComponent">添加组件</button>
<div v-for="(comp, index) in components" :key="index">
<component :is="comp.type" @remove="removeComponent(index)"></component>
</div>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: { ComponentA, ComponentB },
data() {
return {
components: [],
nextComponent: 0
}
},
methods: {
addComponent() {
this.components.push({
type: this.nextComponent % 2 === 0 ? 'ComponentA' : 'ComponentB'
})
this.nextComponent++
},
removeComponent(index) {
this.components.splice(index, 1)
}
}
}
</script>
注意事项
为每个动态生成的元素添加唯一的 key 属性,帮助 Vue 高效地更新 DOM。
避免直接操作 DOM,始终通过修改数据来驱动视图变化。
对于大型列表,考虑使用虚拟滚动技术优化性能。







