<template>
<a-table
:data-source="resultData"
:pagination="false"
:loading="executeLoading"
>
<a-table-column
v-for="item in columns"
:key="item.dataIndex"
:data-index="item.dataIndex"
>
<template #title>
<a-popover :trigger="hasHeaderOverflow[item.dataIndex] ? 'hover' : 'none'">
<span slot="content">{{ item.title }}</span>
<div
:ref="el => headerRefs[item.dataIndex] = el"
class="ellipsis"
>
{{ item.title }}
</div>
</a-popover>
</template>
<template slot-scope="text, record, index">
<a-popover :trigger="hasOverflow[index]?.[item.dataIndex] ? 'hover' : 'none'">
<span slot="content">{{ text }}</span>
<div
:ref="el => ((cellRefs[index] || (cellRefs[index] = {})), cellRefs[index][item.dataIndex] = el)"
class="ellipsis"
>
{{ text }}
</div>
</a-popover>
</template>
</a-table-column>
</a-table>
</template>
<script setup>
import { ref, watch, nextTick } from 'vue';
const resultData = ref(null);
const executeLoading = ref(false);
const getResult = async () => {
const { data } = await query();
resultData.value = data;
};
// 表格相关
const columns = computed(() => Object.keys(resultData.value?.[0] ?? {}).map(k => ({ dataIndex: k, title: k })));
const hasOverflow = ref([]);
const hasHeaderOverflow = ref({});
const cellRefs = ref([]);
const headerRefs = ref({});
watch(resultData, (value) => {
if (value) {
const checkOverflow = element => element.scrollWidth > element.clientWidth;
hasOverflow.value = [];
hasHeaderOverflow.value = {};
cellRefs.value = [];
headerRefs.value = {};
nextTick(() => {
Object.keys(value[0] ?? {}).forEach((k) => {
const ele = headerRefs.value[k];
ele && (hasHeaderOverflow.value[k] = checkOverflow(ele));
});
value.forEach((item, index) => {
Object.keys(item).forEach((k) => {
const ele = cellRefs.value[index]?.[k];
ele && ((hasOverflow.value[index] || (hasOverflow.value[index] = {})), hasOverflow.value[index][k] = checkOverflow(ele));
});
});
});
}
});
</script>
<style>
.ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
Vue 给所有表格单元格加省略号与hover提示
于 2024-07-17 15:43:11 首次发布