在 Vue.js 中,可以通过修改数据来实现关闭展开的其他行。首先,在组件的 data 属性中定义一个变量,用于记录当前展开的行的索引。然后,在展开行的事件处理方法中,将该变量更新为当前展开行的索引。接下来,可以在 el-table 组件的每一行中绑定展开按钮,并通过判断当前行的索引与记录的索引是否相同来确定是否展开。如果索引相同,则展开该行;否则,关闭该行。

下面是一个示例代码:

<template>
  <el-table :data="tableData" @expand-change="expandClick">
    <el-table-column type="expand">
      <template slot-scope="props">
        <el-button @click="expandRow(props.row)">展开</el-button>
      </template>
    </el-table-column>
    <el-table-column prop="name" label="姓名"></el-table-column>
    <el-table-column prop="age" label="年龄"></el-table-column>
    <el-table-column prop="gender" label="性别"></el-table-column>
  </el-table>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { name: '张三', age: 20, gender: '男' },
        { name: '李四', age: 22, gender: '女' },
        { name: '王五', age: 25, gender: '男' }
      ],
      expandedRow: -1
    };
  },
  methods: {
    expandClick(row, expandedRows) {
      // 记录当前展开的行的索引
      this.expandedRow = expandedRows.length > 0 ? expandedRows[0].$index : -1;
    },
    expandRow(row) {
      // 切换展开状态时,关闭其他展开的行
      if (this.expandedRow !== -1) {
        this.$refs.table.toggleRowExpansion(this.expandedRow, false);
      }
      this.$refs.table.toggleRowExpansion(row, true);
    }
  }
};
</script>

在上面的示例中,展开按钮的点击事件绑定了`expandRow`方法,该方法用于切换行的展开状态。在`expandRow`方法中,首先判断当前是否有其他行已展开,如果有,则通过`toggleRowExpansion`方法关闭其他展开的行;然后,再通过`toggleRowExpansion`方法展开或关闭当前行。注意,`$refs.table`是 el-table 组件的引用,可以通过该引用调用 el-table 的方法。

通过以上方式,可以实现展开一条记录时,关闭其他展开的行。

Vue.js 中实现展开一条记录时关闭其他展开行的 el-table 解决方案

原文地址: https://www.cveoy.top/t/topic/o9dH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录