1、实现的效果图
a、正常情况下:
b、点击某项并且是可编辑时,显示input框并自动获取焦点:
c、当input框失去焦点或者改变值按回车,又变回a图
2、重点代码
(1)html部分
<el-table-column v-for="it in xmls" :key="it.id" :label="it.name" :prop="it.code" width="100" :show-overflow-tooltip="true" align="right" > <template scope="scope"> <span v-if="it.editeFlag&&scope.row[it.code].editing" style="display:inline-block;100%;height:100%;" > <el-input ref="inputRef" v-model="scope.row[it.code].value" placeholder="请输入内容" @change="closeEdit(scope.row,it)" @blur="closeEdit(scope.row,it)" /> </span> <span v-if="!scope.row[it.code].editing" style="display:inline-block;100%;height:100%;" @click="handleEdit(scope.row,it)" >{{scope.row[it.code].value}}</span> </template> </el-table-column>
(2)js
methods: { handleEdit(row, it) { //遍历数组改变editeFlag if (it.editeFlag) { row[it.code].editing = true; this.$nextTick(function() { //DOM 更新了 console.log(this.$refs.inputRef); this.$refs.inputRef[0].focus(); }); } }, closeEdit(row, it) { row[it.code].editing = false; } }
(3)数据:
this.xmls = [ { id: 1, name: "A", code: "aaa", editeFlag: true }, { id: 2, name: "B", code: "bbb", editeFlag: false },//定义第二列不能编辑 { id: 3, name: "C", code: "ccc", editeFlag: true } ]; this.items = [ { id: 11, xm: "A资金", num: 1, aaa: { value: "Aa1", editing: false//定义数据是否在编辑状态 }, bbb: { value: "Bb1", editing: false }, ccc: { value: "Cc1", editing: false } }, { id: 12, xm: "B资金", num: 2, aaa: { value: "Aa2", editing: false }, bbb: { value: "Bb2", editing: false }, ccc: { value: "Cc2", editing: false } }, { id: 13, xm: "C资金", num: 3, aaa: { value: "Aa3", editing: false }, bbb: { value: "Bb3", editing: false }, ccc: { value: "Cc3", editing: false } } ];
3、this.$refs.inputRef[0].focus();要用0的原因
(1)注意看,ref="inputRef"是位于v-for里面的,所以this.$refs.inputRef得到的是数组,如下图
(2)再做一个测试,在固定的表头加个ref,如下图
所以,ref="inputRef"是位于v-for里面的,当然得用this.$refs.inputRef[0].focus();
而不是this.$refs.inputRef.focus();这个会报focus不是函数的错误。
最后: