Bootstrap

el-table表格点击单元格实现编辑

 

  1. 使用 el-table 和 el-table-column 创建表格。
  2. 在单元格的默认插槽中,使用 div 显示文本内容,单击时触发编辑功能。
  3. 使用 el-input 组件在单元格中显示编辑框。
  4. data() 方法中定义了 tableData,tabClickIndex: null,tabClickLabel: '',用于判断是否处于编辑转态
  5. @cell-click="tabClick" 方法用于将单元格设置为编辑状态,并使用 this.$nextTick 来确保输入框能获得焦点。
  6. 通过blur监听失去焦点。

<template>
  <div>
    <el-table :data="dataDetail" :row-class-name="tableRowClassName" border style="width: 100%" max-height="500px" @cell-click="tabClick">
      <el-table-column prop="test1" label="test1" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.index === tabClickIndex && tabClickLabel === 'test1'">
            <el-input :ref="'test1'+scope.row.id" v-model="scope.row.test1" maxlength="300" placeholder="请输入test1" size="mini" @blur="inputBlur" />
          </span>
          <span v-else>{
  
  { scope.row.test1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="test2" label="test2" width="120px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.index === tabClickIndex && tabClickLabel === 'test2'">
            <el-input :ref="'test2'+scope.row.id" v-model="scope.row.test2" :blur="inputBlur" placeholder="请输入test2" size="mini" @blur="inputBlur" />
          </span>
          <span v-else>{
  
  { scope.row.test2 | fmoney }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="test3" label="test3" align="center" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.index === tabClickIndex && tabClickLabel === 'test3'">
            <el-input :ref="'test3'+scope.row.id" v-model="scope.row.test3" maxlength="300" placeholder="请输入test3" size="mini" @blur="inputBlur" />
          </span>
          <span v-else>{
  
  { scope.row.test3 }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>

</template>

<script>
export default {
  data () {
    return {
      tabClickIndex: null, // 点击的单元格
      tabClickLabel: '', // 当前点击的列名
      dataDetail: [{ id: '123', test1: 'sss' }, { id: '456', test1: 'sss' }]
    }
  },
  methods: {
    tableRowClassName ({ row, rowIndex }) {
  
      row.index = rowIndex
    },
   
    tabClick (row, column, cell, event) {
      switch (column.label) {
        case 'test1':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case 'test2':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case 'test3':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        default: return
      }
      const key = this.tabClickLabel + row.id
      this.$nextTick(() => {
        this.$refs[key].focus()
      })
    },
  
    inputBlur (row, event, column) {
      this.tabClickIndex = null
      this.tabClickLabel = ''
    },
  }
}
</script>

<style>
</style>

;