<template>
<div>
<table>
<thead>
<tr>
<th v-for="(header, index) in headers" :key="index">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex">
<input
v-if="editingCell === `${rowIndex}-${cellIndex}`"
v-model="tableData[rowIndex][cellIndex]"
@blur="editingCell = null"
@keyup.enter="editingCell = null"
/>
<span v-else @dblclick="editCell(rowIndex, cellIndex)">
{{ cell }}
</span>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
headers: ["Name", "Age", "City"],
tableData: [
["Alice", 24, "New York"],
["Bob", 30, "San Francisco"],
["Charlie", 28, "Los Angeles"]
],
editingCell: null
};
},
methods: {
editCell(row, cell) {
this.editingCell = `${row}-${cell}`;
}
}
};
</script>
<style scoped>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
</style>
模板部分 (<template>):
<thead>) 和表格主体 (<tbody>)。v-for 指令动态生成。v-for 动态生成。每个单元格可以是可编辑的输入框或静态文本。脚本部分 (<script>):
headers 数组来存储表头信息。tableData 是一个二维数组,存储表格的数据。editingCell 变量用于跟踪当前正在编辑的单元格的位置。editCell 方法用于切换单元格的编辑状态。样式部分 (<style scoped>):
这个示例展示了如何使用 Vue.js 创建一个简单的可编辑表格。用户可以通过双击单元格进入编辑模式,并在编辑完成后自动保存更改。
上一篇:vue自定义事件
下一篇:vue表单校验
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站