方法一:使用 empty-text 属性
html
<el-table :data="tableData" empty-text="暂无数据">
<!-- 列定义 -->
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
方法二:使用空数组并设置默认行
javascript
import { ref } from 'vue';
const tableData = ref([{}]); // 默认包含一个空对象
html
<el-table :data="tableData">
<!-- 列定义 -->
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
</el-table>
方法三:自定义空状态插槽
html
<el-table :data="tableData">
<!-- 列定义 -->
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<template #empty>
<el-table-row>
<el-table-column :span="2">暂无数据</el-table-column>
</el-table-row>
</template>
</el-table>
方法四:始终显示一行(即使数据为空)
javascript
import { ref, computed } from 'vue';
const realData = ref([]); // 实际数据
const tableData = computed(() => {
return realData.value.length > 0 ? realData.value : [{}];
});
注意事项
-
如果使用空对象作为默认行,表格中的列可能会显示为空白
-
对于需要特殊样式的默认行,可以通过 row-class-name 属性添加自定义类名
-
如果需要在默认行中添加特定的占位文本,可以在列定义中使用插槽
html<el-table-column prop="name" label="姓名"> <template #default="{ row }"> {{ row.name || '-' }} </template> </el-table-column>