效果图:
文本切换表单控件有以下几个关键点:
1、控制显示隐藏的cellNameVisible属性要放在表格源数据(tableData)中。
2、下面的源码tableData是直接写死的,项目中我们是要请求接口的,此时我们需要先定义一个临时数组arr,把所有需要的属性都先放进去,包括控制文本切换的cellNameVisible属性,最后再赋值给表格的源数据tableData,要不然后面点击文本切换的时候,表格视图是不会正常更新的。
代码如下:
async associatedSubList(params) {
//接口请求
let res = await this.$store.dispatch("plan/associatedSubList", params);
if (res.code == 20000) {
if (res.data && res.data.length > 0) {
const arr = JSON.parse(JSON.stringify(res.data));
arr.forEach(item => {
item["cellNameVisible"] = false; //控制文本和input控件的切换
})
this.tableData = arr;
}
}
},
3、由于文本切换成input框需要一定的时间,所以我们在让input获取焦点的时候,必须确保input已经存在了,在这里我们用到了vue的this.$nextTick(()=>{}),等dom更新完成之后,再来获取焦点。
源码
<el-table
:data="tableData"
border
:header-cell-style="{background:'#f5f7fa',color:'#909399'}"
style="width: 100%">
<el-table-column prop="date" label="日期" align="center"></el-table-column>
<el-table-column prop="name" label="姓名" align="center">
<template slot-scope="scope">
<span
v-if="!scope.row.cellNameVisible"
@click="cellClick(scope.row)"
>{{ scope.row.name }}</span>
<el-input
ref="inputFocus"
v-if="scope.row.cellNameVisible"
v-model="scope.row.name"
@blur="blurEvent(scope.row)"
>
</el-input>
</template>
</el-table-column>
<el-table-column prop="address" align="center" label="地址"></el-table-column>
</el-table>
// data中
tableData: [{
id: 1,
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄',
cellNameVisible: false,
}, {
id: 2,
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄',
cellNameVisible: false,
}, {
id: 3,
date: '2016-05-01',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄',
cellNameVisible: false,
}, {
id: 4,
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄',
cellNameVisible: false,
}]
//methods中
/**
* 点击文本显示input框,隐藏文本
*/
cellClick(row) {
row.cellNameVisible = true;
this.$nextTick(() => {
this.$refs.inputFocus.focus();
});
},
/**
* input失去焦点之后隐藏input框,重新显示出文本
*/
blurEvent(row) {
row.cellNameVisible = false;
}