Vue 给所有表格单元格加省略号与hover提示

<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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值