vue实现添加行
Vue 实现添加行的基本方法
在 Vue 中实现表格或列表的动态添加行功能,可以通过操作数据数组结合 v-for 指令完成。以下是两种常见场景的实现方式:
基础表格添加行
<template>
<div>
<table>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
<button @click="addRow">添加行</button>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ name: '默认行', value: 0 }
]
}
},
methods: {
addRow() {
this.items.push({
name: '新行',
value: this.items.length
})
}
}
}
</script>
表单输入添加行
对于需要用户输入后添加的场景:
<template>
<div>
<input v-model="newItem.name" placeholder="名称">
<input v-model="newItem.value" placeholder="值" type="number">
<button @click="addRow">添加</button>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }}: {{ item.value }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
newItem: { name: '', value: 0 },
items: []
}
},
methods: {
addRow() {
if (this.newItem.name.trim()) {
this.items.push({...this.newItem})
this.newItem = { name: '', value: 0 } // 重置表单
}
}
}
}
</script>
使用 Vue 3 Composition API
Vue 3 的响应式系统可以更简洁地实现:
<template>
<button @click="addRow">添加随机数据行</button>
<div v-for="(row, index) in rows" :key="index">
行 {{ index }}: {{ row.data }}
</div>
</template>
<script setup>
import { ref } from 'vue'
const rows = ref([])
const addRow = () => {
rows.value.push({
data: Math.random().toString(36).substring(7)
})
}
</script>
注意事项
- 为动态生成的元素添加唯一
key属性,通常使用索引或唯一ID - 复杂表格建议使用专门的表格组件库如
Element UI或Vuetify - 大量数据时考虑虚拟滚动优化性能
扩展功能
实现可删除行的完整示例:
<template>
<div>
<button @click="addRow">+ 添加行</button>
<table>
<tr v-for="(row, index) in rows" :key="row.id">
<td><input v-model="row.content"></td>
<td><button @click="removeRow(index)">删除</button></td>
</tr>
</table>
</div>
</template>
<script>
export default {
data() {
return {
rows: [],
nextId: 1
}
},
methods: {
addRow() {
this.rows.push({
id: this.nextId++,
content: ''
})
},
removeRow(index) {
this.rows.splice(index, 1)
}
}
}
</script>






