You need to enable JavaScript to run this app. Vue.js+Element UI如何正确获取el-table行ID实现用户删除
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js+Element UI如何正确获取el-table行ID实现用户删除

Element UI 表格行操作获取主键ID实现说明

业务场景

需要获取<el-table-column>对应行的唯一ID,调用后端接口完成MySQL查询返回用户数据的删除操作。
表格实际渲染效果:
表格效果截图

现有实现代码

  1. 基础用户表格代码
<el-table
  :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
  max-height="500">
  <el-table-column
    prop="id"
    label="Id"
    width="150">
  </el-table-column>
  <el-table-column
    prop="username"
    label="Username"
    width="120">
  </el-table-column> 
  <!-- 其他省略列 -->
</el-table>
  1. 操作列现有实现代码
<el-table-column
  align="right"
  fixed="right"
  width="150px">
  <template slot="header" slot-scope="scope">
    <el-input
      v-model="search"
      size="mini"
      placeholder="Username"/>
  </template>
  <template slot-scope="scope">
   <button class="buttons-edit edit" @click.prevent="deleteUser(tableData[scope.$index].id)">editar</button>
   <button class="buttons-edit delete" @click.prevent="deleteUser(tableData[scope.$index].id)">Eliminar</button>
  </template>
</el-table-column>

现存问题

  • 曾尝试通过tableData[scope.$index].putLink获取行ID,始终无法得到预期参数值
  • 无法为删除方法正确传入对应的用户ID参数

问题根因

  • 索引错位问题:el-table绑定的数据源是经过搜索过滤后的临时数组,直接用过滤后数组的scope.$index匹配原始未过滤的tableData数组取值,一旦搜索框输入筛选内容,行索引和原始数据就会完全错位,无法取到正确的ID
  • 冗余取值逻辑:Element UI 列作用域插槽本身内置了当前行的完整数据对象scope.row,完全不需要手动通过数组索引回溯数据源,从根源上可以避免筛选、排序、分页导致的索引错位问题
  • 逻辑绑定错误:编辑按钮当前和删除按钮绑定了同一个deleteUser方法,存在功能混淆
  • 方法取值错误:删除方法的确认提示中错误使用了组件实例的this.id属性,没有正确拼接传入的用户ID参数

修正后实现

  1. 操作列取值修正
    直接从作用域插槽的scope.row中读取当前行的主键ID,不再通过数组索引回溯数据源,示例代码:
<template slot-scope="scope">
  <button 
    class="buttons-edit edit" 
    @click.prevent="editUser(scope.row.id)">
    editar
  </button>
  <button 
    class="buttons-edit delete" 
    @click.prevent="deleteUser(scope.row.id)">
    Eliminar
  </button>
</template>
  1. 删除方法修正
    修正确认提示的参数取值,保持和传入的ID参数一致,示例代码:
deleteUser(id) {
  if (window.confirm(`Desea eliminar el usuario con ID ${id}?`)) {
    console.log("Eliminado");
    this.$http.post(`user/delete/${id}`).then(res => {
      if (res.status == 200) {
        alert("Se ha eliminado el usuario!");
        this.getUsers();
      }
    });
  } else {
    this.$alert("Cancelado", "", {
      type: "error",
      showClose: false,
      duration: 600
    });
  }
}

内容的提问来源于stack exchange,提问作者Sebas Carrillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 21:45:02