两种编辑类型:
1、双击单元格,编辑当前单元格
2、点击编辑按钮,编辑整行
第一种:
1、思路
通过一个数组记录编辑状态(也可以是绑定数据的某个属性,如果是多列可编辑,你可能需要多个数组或者属性),双击单元格,编辑状态设置为true,切换显示的文本内容为input输入框,当input输入框失去焦点时,保存数据,编辑状态设置为false。
2、关键代码
<el-table :data="data" @cell-dblclick="handleCellDblclick">
<el-table-column prop="name" label="姓名">
<template slot-scope="scope">
<span v-if="showEdit[scope.$index]">
<el-input size="small" v-model="scope.row.name" @blur="handleInputBlur(scope.$index)"></el-input>
</span>
<span v-else>{{scope.row.name}}</span>
</template>
</el-table-column>
</el-table>
其中“showEdit”是保存编辑状态的数组
定义单元格的双击事件:@cell-dblclick="handleCellDblclick"
handleCellDblclick(row, column) {
this.$set(this.showEdit, row.index, true)
}
input输入框失去焦点事件:
handleInputBlur (index) {
this.$set(this.showEdit, index, false)
}
第二种:
1、思路
通过绑定数据的一个属性,记录当前行的编辑状态。当点击编辑按钮时,编辑状态设置为true。
2、关键代码
<el-table :data="data">
<el-table-column prop="name" label="姓名">
<template slot-scope="scope">
<span v-if="scope.row.edit">
<el-input size="small" v-model="scope.row.name"></el-input>
</span>
<span v-else>{{scope.row.name}}</span>
</template>
</el-table-column>
<el-table-column fixed="right" label="操作">
<template slot-scope="action">
<el-button v-if="action.row.edit === true" type="text" size="small" @click="handleSave(action.row)">保存</el-button>
<el-button v-else type="text" size="small" @click="handleEdit(action.row)">编辑</el-button>
</template>
</el-table-column>
</el-table>
handleEdit(row) {
row.edit = true
}
handleSave(row) {
row.edit = false
}