vue实现输入表格
Vue 实现输入表格的方法
使用 v-for 动态渲染表格
通过 Vue 的 v-for 指令动态渲染表格行和列,结合 v-model 实现双向数据绑定。
<template>
<table>
<thead>
<tr>
<th v-for="(header, index) in headers" :key="index">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">
<input v-model="rows[rowIndex][cellIndex]" />
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
rows: [
['', '', ''],
['', '', '']
]
};
}
};
</script>
动态添加和删除行
通过方法动态操作 rows 数组,实现表格行的增删功能。
<template>
<div>
<button @click="addRow">添加行</button>
<button @click="removeRow">删除行</button>
<table>
<!-- 表格内容同上 -->
</table>
</div>
</template>
<script>
export default {
methods: {
addRow() {
this.rows.push(new Array(this.headers.length).fill(''));
},
removeRow() {
if (this.rows.length > 1) {
this.rows.pop();
}
}
}
};
</script>
表单验证
结合计算属性或第三方库(如 Vuelidate)对输入内容进行验证。
<template>
<table>
<tr v-for="(row, rowIndex) in rows" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">
<input
v-model="rows[rowIndex][cellIndex]"
:class="{ 'error': !isValid(rowIndex, cellIndex) }"
/>
</td>
</tr>
</table>
</template>
<script>
export default {
computed: {
isValid() {
return (rowIndex, cellIndex) => {
return this.rows[rowIndex][cellIndex].trim() !== '';
};
}
}
};
</script>
<style>
.error {
border: 1px solid red;
}
</style>
使用组件化实现
将表格行或单元格封装为独立组件,提高代码复用性。

<template>
<table>
<tbody>
<table-row
v-for="(row, index) in rows"
:key="index"
:row-data="row"
@update="updateRow(index, $event)"
/>
</tbody>
</table>
</template>
<script>
import TableRow from './TableRow.vue';
export default {
components: { TableRow },
data() {
return { rows: [['张三', '25'], ['李四', '30']] };
},
methods: {
updateRow(index, newRow) {
this.$set(this.rows, index, newRow);
}
}
};
</script>
表格行组件示例
<!-- TableRow.vue -->
<template>
<tr>
<td v-for="(cell, index) in rowData" :key="index">
<input v-model="localRow[index]" @input="onInput" />
</td>
</tr>
</template>
<script>
export default {
props: ['rowData'],
data() {
return { localRow: [...this.rowData] };
},
methods: {
onInput() {
this.$emit('update', this.localRow);
}
}
};
</script>
注意事项
- 使用
v-for时必须添加:key以提高渲染性能 - 深层数据修改时建议使用
Vue.set或数组的变异方法 - 复杂场景可考虑使用 Vuex 管理表格数据状态
- 移动端适配需额外处理输入框的样式和交互
以上方法可根据实际需求组合使用,例如同时实现动态增删行、表单验证和组件化架构。






