el-table实现行内编辑
时间: 2025-01-10 21:28:54 浏览: 35
Element UI 的 el-table
组件实现行内编辑
为了实现在 el-table
中的行内编辑功能,可以通过监听特定事件并控制每一行的状态来切换输入模式和查看模式。下面是一个完整的示例说明如何通过点击编辑按钮触发行内编辑。
HTML 结构
<template>
<div id="app">
<el-table :data="tableData" style="width: 100%">
<!-- 定义表格列 -->
<el-table-column label="日期" width="180">
<template slot-scope="scope">
<span v-if="!scope.row.edit">{{ scope.row.date }}</span>
<el-input v-else v-model="scope.row.date"></el-input>
</template>
</el-table-column>
<el-table-column label="姓名" width="180">
<template slot-scope="scope">
<span v-if="!scope.row.edit">{{ scope.row.name }}</span>
<el-input v-else v-model="scope.row.name"></el-input>
</template>
</el-table-column>
<el-table-column label="地址">
<template slot-scope="scope">
<span v-if="!scope.row.edit">{{ scope.row.address }}</span>
<el-input v-else v-model="scope.row.address"></el-input>
</template>
</el-table-column>
<el-table-column fixed="right" label="操作" width="120">
<template slot-scope="scope">
<el-button @click.prevent="editRow(scope.$index)" type="text">编辑</el-button>
<el-button @click.prevent="saveRow(scope.$index)" type="text">保存</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
JavaScript 部分
<script>
export default {
data() {
return {
tableData: [
{ date: '2016-05-03', name: 'Tom', address: 'No. 189, Grove St, Los Angeles', edit: false },
{ date: '2016-05-02', name: 'John', address: 'New York No. 1 Lake Park', edit: false }
]
};
},
methods: {
// 编辑当前行
editRow(index) {
this.tableData[index].edit = true;
},
// 保存修改后的数据
saveRow(index) {
this.tableData[index].edit = false;
console.log('Updated Data:', this.tableData);
// 此处可加入API调用来提交更改到服务器
}
}
};
</script>
此代码片段展示了怎样利用 Vue.js 和 Element UI 来创建一个支持行内编辑的表格[^1]。当用户点击“编辑”按钮时,对应行进入编辑状态;而点击“保存”则会结束编辑并将新值应用回原始对象上。此外,在实际项目中可能还需要考虑验证逻辑以及向后台发送更新请求等功能扩展[^5]。
相关推荐

















