You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Element UI拖拽表格编辑保存后保持行展开状态的问题

问题:Element UI拖拽表格编辑保存后展开状态丢失

我基于Element UI实现了一个可拖拽表格,点击编辑按钮打开弹窗完成编辑保存后,所有已展开的行都会自动收起。需要实现保存操作完成后,保持之前的行展开状态。

相关代码

模板部分

<table-card>
  <el-table-draggable @drop="changeDossiertypesOrder" handle=".handler">
    <el-table
      :data="dossiertypes"
      v-loading="dossiertypesLoading"
      row-key="id"
      :expand-row-keys="expandRowKeys"
      @expand-change="handleExpandChange"
    >
      <el-table-column type="expand">
      </el-table-column>
    </el-table>
  </el-table-draggable>
</table-card>

<el-dialog      
  :visible.sync="modalVisibility"
  :close-on-click-modal="false"
  :show-close="false"
  @open="resetForm"
  @opened="$refs.defaultField[0].focus()"
  @closed="resetForm"
>
  <template v-slot:footer>
    <div>
      <c-button type="primary" icon="check" @click="saveType" :loading="isSaving.editType">Save</c-button>
    </div>
  </template>
</el-dialog>

脚本部分

展开状态处理函数

handleExpandChange(row, expandedRows) {
  const id = row.id;
  const lastId = this.expandRowKeys[0];
  // 禁用多行展开
  this.expandRowKeys = id === lastId ? [] : [id];
},

保存函数

saveType() {
  this.isSaving.editType = true;
  axios
    .put()
    .then(() => {
      this.expandRowKeys = [...this.expandRowKeys];
    })
    .finally(() => {
      this.isSaving.editType = false;
    });
},

解决方案

1. 排查状态重置源头

先检查resetForm函数,确认其中是否包含重置expandRowKeys的逻辑(比如this.expandRowKeys = [])。如果有,移除这部分代码,只重置表单相关变量,避免影响展开状态。

2. 保存并恢复展开状态

如果保存操作会重新获取表格数据,需要在请求前先记录当前展开的行ID,数据更新后再恢复对应状态:

saveType() {
  this.isSaving.editType = true;
  // 提前保存当前展开的行ID
  const savedExpandIds = [...this.expandRowKeys];
  
  axios
    .put('/your-api-path', yourEditData) // 补充实际请求地址和参数
    .then(() => {
      // 重新获取最新表格数据(如果业务需要)
      return axios.get('/your-data-api');
    })
    .then(res => {
      this.dossiertypes = res.data;
      // 恢复展开状态,过滤掉已不存在的行ID
      this.expandRowKeys = savedExpandIds.filter(id => 
        this.dossiertypes.some(item => item.id === id)
      );
    })
    .finally(() => {
      this.isSaving.editType = false;
      this.modalVisibility = false; // 关闭弹窗
    });
},

3. 确保响应式更新正确

如果保存操作只是更新现有数据中的某一行,无需重新请求数据,只需确保expandRowKeys的响应式更新正确。你当前代码中this.expandRowKeys = [...this.expandRowKeys]的写法已经能触发响应式更新,只需确保表格数据更新时不会触发展开状态的意外重置即可。

内容的提问来源于stack exchange,提问作者Yellow rain coat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:54:38