likes
comments
collection
share

elementUi table点击可编辑--简单实现

作者站长头像
站长
· 阅读数 18

工作中的需求,找了多个地方总结出来的,给有需要的小伙伴!

elementUi table点击可编辑--简单实现

elementUi table点击可编辑--简单实现

 <el-table :data="powerMessageTableAll" border :cell-class-name="tableCellClassName" @cell-click="handleCurrentChange">
    <el-table-column label="名字" prop="name" align="center">
        <template slot-scope="scope">
            <el-input v-if="scope.row.index === tabClickIndex && scope.column.index === tableCellClickColumnIndex" 
            ref="gain" v-model="scope.row.name" type="input" style="width: 100%;hight:100%" 
            @blur="handleSave(scope)" />
            <span v-else>{{ scope.row.name }}</span>
        </template>
    </el-table-column>
    <el-table-column label="时间" prop="ctime" align="center">
        <template slot-scope="scope">
            <el-date-picker v-if="scope.row.index === tabClickIndex && scope.column.index === tableCellClickColumnIndex" 
             ref="gain" v-model="scope.row.ctime" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width: 100%;hight:100%" 
             @blur="handleSave(scope)" />
            <span v-else>{{ scope.row.ctime }}</span>
        </template>
    </el-table-column>
</el-table>
data:{
     tabClickIndex: null, // 点击的单元
     tableCellClickColumnIndex: null,
      powerMessageTableAll: [
        {
          name: "小红",
          ctime: "2017-08-14",
        },
        {
          name: "小名",
          ctime: "2022-08-14",
        },
      ],
}
tableCellClassName({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex;
      column.index = columnIndex;
    },
handleCurrentChange(row, column, event) {
  this.tabClickIndex = row.index;
  this.tableCellClickColumnIndex = column.index;
  this.$nextTick(() => {
    this.$refs.gain.focus(); //显示文本框并获取焦点
  });
},
handleSave() {
  this.tabClickIndex = null;
  this.tableCellClickColumnIndex = null;
},
//聚焦这块有优化的空间,应该是让当前选择的input框聚焦,
JS都忘差不多,也没有去找,应该是event找到对应的子元素然后focus的,
工作中的小伙伴有优化的话,麻烦在底下贴下!