1.第一种方式:循环往表格的数组对象里面添加控制可不可编辑的状态字段
(1)表格的基本架子
<el-table
:data="rwsDetails"
border
class="table"
ref="mxMultipleTable"
header-cell-class-name="table-header"
@selection-change="mxHandleSelectionChange"
@row-click="mxHandleRowClick"
@cell-dblclick="cellEdit">
<el-table-column prop="grgzrwsId" v-if="false" label="ID" width="55" align="center"></el-table-column>
<el-table-column prop="rymc.value" label="被考核人" width="150px" align="center">
</el-table-column>
<el-table-column prop="jffz" label="加分值" align="center">
<template slot-scope="scope">
<el-input-number v-if="scope.row.jffz.edit" v-model="scope.row.jffz.value" @blur="loseFocus(scope.row.jffz)" ref="jffz"></el-input-number>
<span v-else>{{scope.row.jffz.value}}</span>
</template>
</el-table-column>
<el-table-column prop="jfyy" label="加分原因" align="center">
<template slot-scope="scope">
<el-input v-if="scope.row.jfyy.edit" v-model="scope.row.jfyy.value" @blur="loseFocus(scope.row.jfyy)" ref="jfyy"></el-input>
<span v-else>{{scope.row.jfyy.value}}</span>
</template>
</el-table-column>
</el-table>
(2)绑定的事件
// 将所有单元格设置为不可编辑
initialTableEdit(bo) {
this.rwsDetails.forEach((item) => {
for (let i in item) {
item[i] = {
value: item[i],
edit: false
}
}
})
},
// 单元格双击事件
cellEdit(row, column) {
// 将单元格变为输入框
row[column.property].edit = true
// 聚焦到单元格
setTimeout(() => {
this.$refs[column.property].focus()
}, 20)
},
// 当输入框失去焦点时不显示输入框
loseFocus(editCell) {
editCell.edit = false
},
2.第二种方式:对于字段少的表格,可以每个设置一个控制状态的字段
(1)表格基本架子:
<el-table :data="a(item)"
border
class="tb-edit"
@cell-click="cellClick"
style="width: 100%;font-size: 24px"
:row-style="{height:'50px'}">
<el-table-column prop="bh"
label="编号"
align="center"
show-overflow-tooltip>
<template slot-scope="scope">
<el-input v-model="scope.row.bh"
v-if="scope.row.flag"
@blur="inputClick(scope.row,'1')"
v-focus></el-input>
<span v-if="!scope.row.flag">{{scope.row.bh}}</span>
</template>
</el-table-column>
<el-table-column prop="yplx"
label="值"
align="油品类型"
show-overflow-tooltip>
<template slot-scope="scope">
<el-input v-model="scope.row.yplx"
v-if="scope.row.flagone"
@blur="inputClick(scope.row)"
v-focus></el-input>
<span v-if="!scope.row.flagone">{{scope.row.yplx}}</span>
</template>
</el-table-column>
</el-table>
(2)初始化
tableData: [{
bh: '',
yplx: '#95',
flag: false,
flagone: false
}, {
bh: '',
yplx: '#95',
flag: false,
flagone: false
}],
(3)事件
// 双击单元格后,显示input,并通过v-focus让input自动获取焦点
cellClick (row, column) {
if (column.property == 'bh') {
row.flag = true
} else {
row.flagone = true
}
},
// input框失去焦点事件
inputClick (row, a) {
if (a == '1') {
row.flag = false
} else {
row.flagone = false
}
}
4.自定义指令获取焦点
directives: {
// 注册一个局部的自定义指令 v-focus
focus: {
// 指令的定义
inserted: function (el) {
// 聚焦元素
el.querySelector('input').focus()
}
}
},