我们在使用 Element Plus 表格 Table 开发前端功能时,常常会使用树形表格的展开和收缩行功能,下面记录其使用方法:

先看 Table 官方文档里的关键属性:

属性名说明类型Default
default-expand-all是否默认展开所有行,当 Table 包含展开行存在或者为树形表格时有效booleanfalse

关键代码:

// 模板代码
<el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
<el-table :default-expand-all="isExpandAll">

// js代码
<script setup>
import { ref } from 'vue'
const isExpandAll = ref(false)
const toggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
}
</script>

运行以上代码,发现点击 展开/折叠 按钮,表格没有任何反应,好像 default-expand-all 完全失效了。那是因为改变该值视图没有同步刷新。

解决方案:

方法1:

// 模板代码
<el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
<el-table v-if="isShow" :default-expand-all="isExpandAll">

// js代码
<script setup>
import { ref, nextTick } from 'vue'
const isShow = ref(true)
const isExpandAll = ref(false)
const toggleExpandAll = async () => {
  isShow.value = false
  isExpandAll.value = !isExpandAll.value
  await nextTick()
  isShow.value = true
}
</script>

方法2:

// 模板代码
<el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
<el-table :key="tableKey" :default-expand-all="isExpandAll">

// js代码
<script setup>
import { ref } from 'vue'
const tableKey = ref(+new Date())
const isExpandAll = ref(false)
const toggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
  tableKey.value = +new Date()
}
</script>

ElementUI 中使用类似。

如果觉得我的文章对你有用,请点个赞