展示效果
在el-table
组件中有默认展开的属性expand-row-keys
需要配合row-key
使用,可能是我用的方式不对,用了不生效。所以我索性换一种解决方案。通过 Vue 的 ref 方法手动展开第一行。
1. 在 el-table 组件上添加 ref
首先,给 el-table 组件添加一个 ref,用于在代码中引用这个表格。
<el-table
ref="performanceTable"
row-key="performanceId"
v-loading="loading"
:data="list">
<!-- 省略内容 -->
</el-table>
2. 在表格数据加载完成后展开第一行
在 mounted
钩子或数据加载完成的回调中,使用 $refs.performanceTable
引用表格,然后调用 expandRow
方法展开第一行。
const loading = ref(true);
const list = ref([
// 示例数据
{ performanceId: 1, yearMonths: '2023-08', totalSelfScore: 90, performanceStatus: 1, performanceScores: [] },
// 其他数据...
]);
const performanceTable = ref(null); // 用于引用表格
onMounted(() => {
loading.value = false; // 停止加载动画
if (list.value.length > 0) {
// 展开第一行
performanceTable.value?.toggleRowExpansion(list.value[0], true);
}
});
3. 展开功能
performanceTable.value?.toggleRowExpansion(list.value[0], true)
这里使用了 toggleRowExpansion
方法来手动展开指定行,第二个参数 true 表示展开。
这个方法默认会触发 @expand-change
事件,如果你希望在不触发事件的情况下展开行,可以考虑将此事件的逻辑放入条件判断中,避免重复处理。
完整示例
<template>
<el-table
ref="performanceTable"
row-key="performanceId"
v-loading="loading"
:data="list">
<el-table-column type="expand" width="120" label="明细">
<template #default="props">
<el-table
v-loading="props.row.loading"
:data="props.row.performanceScores"
:header-cell-style="{'background':'#ecf2ff','font-size':'14px'}"
:row-style="{'background':'#ecf2ff'}"
class="-mt-10px"
size="small">
<!-- 其他内容保持不变 -->
</el-table>
</template>
</el-table-column>
<!-- 其他列配置 -->
</el-table>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const loading = ref(true);
const list = ref([
// 示例数据
{ performanceId: 1, yearMonths: '2023-08', totalSelfScore: 90, performanceStatus: 1, performanceScores: [] },
// 其他数据...
]);
const performanceTable = ref(null); // 用于引用表格
onMounted(() => {
loading.value = false; // 停止加载动画
if (list.value.length > 0) {
// 展开第一行
performanceTable.value?.toggleRowExpansion(list.value[0], true);
}
});
</script>
通过以上方法,在表格加载完成时默认展开第一行。