Element UI表格内容双击可编辑,失去焦点提交内容

在这里插入图片描述
需求就是双击列表中的某一cell,获取焦点时单元格变成input编辑框,失去焦点时如果内容有更改就触发修改的接口,如果内容无更改的话,就不触发。

1.首先给列表绑定双击事件

@row-dblclick="dbclick"

2.给单元格绑定 className 的回调方法,目的是获取选中单元格的行和列的index

:cell-class-name="tableCellClassName"

相关代码如下:
视图部分:

<el-table
  border
  v-loading="loading"
  :data="fingerList"
  @row-dblclick="dbclick"
  :cell-class-name="tableCellClassName"
>
  <el-table-column label="备注" align="center" prop="notes">
    <template slot-scope="scope">
      <!--v-if去判断双击的是不是当前单元格-->
      <el-input
        @blur="updateNotesValue(scope.row)"
        :ref="scope.row.index + ',' + scope.column.index"
        v-model="scope.row.newNotesValue"
        v-if="scope.row.index + ',' + scope.column.index == currentCell">
      </el-input>
      <span v-else>{{ scope.row.notes }}</span>
    </template>
  </el-table-column>
</el-table>

script部分:

export default {
	data() {
	    return {
	      // 用一个字符串来保存当前双击的是哪一个单元格
	      currentCell: null
	   }
	},
	methods: {
		// 给单元格绑定横向和竖向的index,这样就能确定是哪一个单元格
	    tableCellClassName({ row, column, rowIndex, columnIndex }) {
	      row.index = rowIndex;
	      column.index = columnIndex;
	    },
	    // 获得当前双击的单元格的横竖index,然后拼接成一个唯一字符串用于判断,并赋给currentCell
	    // 拼接后类似这样:"1,0","1,1",
	    dbclick(row, column) {
	      this.currentCell = row.index + ',' + column.index;
	      // 这里必须要setTimeout,因为在点击的时候,input才刚被v-if显示出来,不然拿不到dom
	      setTimeout(() => {
	        // 双击后自动获得焦点
	        this.$refs[row.index + ',' + column.index].focus();
	        // row增加一个新的参数,将原先的值赋给新的参数,用来比较是否进行更改
	        this.$set(row, 'newNotesValue', row.notes)
	      })
	    },
	    // 当input失去焦点的时候,隐藏input, 将修改的内容传给后台
	    updateNotesValue(row) {
	      this.currentCell = null
	      // 比较这个单元格的值是否进行了更改,没有更改不进行任何操作,更改了才触发接口
	      if (row.notes !== row.newNotesValue) {
	        const params = { id: row.id, notes: row.newNotesValue }
	        updateNotes(params).then(res => {
	          this.msgSuccess('修改成功')
	          this.getList()
	        })
	      }
	    }
	}
}

借鉴此博客:链接:https://blog.csdn.net/weixin_44057991/article/details/124713407?spm=1001.2014.3001.5506

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值