ant-design中a-table中文字字数过长时显示tooltip
需求
-
a-table表格中文字字数过长时,需要…显示
文字过长时,可以截取字数进行…展示,但是会存在中文和英文长度不一致的问题,所以采用css的方式截取显示…
<span v-if="!isShowHover" class="text-ellipsis"> {{ value }} </span> // 样式部分 .text-ellipsis { max-width: 200px; // 控制最大长度 display: block; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; }
-
字数过长的时候,不需要显示a-tooltip
采用隐藏的span标签,计算完整显示字数时,所需的高度,当高度大于1行时候用js的方式进行判断是否显示
<!-- 隐藏的span标签 -->
<span :ref="`text${id}`" class="disNone">{{ value }}</span>
// 使用 getComputedStyle 方法,获取高度, val 为显示几行
getStyle(val) {
const lineHeight =
getComputedStyle(this.$refs[`text${this.id}${this.type}`]).lineHeight.replace('px', '') - 0 || 20
const height = getComputedStyle(this.$refs[`text${this.id}`]).height.replace('px', '') - 0
if (height > lineHeight * val) {
this.isShowHover = true // 需要显示tooltip
} else {
this.isShowHover = false // 不需要显示tooltip
}
}
// 样式部分 设置隐藏的z-index -1
.disNone {
position: absolute;
top: -10000px;
z-index: -1;
}
- 鼠标hover时需要a-tooltip显示全部内容
<a-tooltip placement="topLeft" :title="value" v-else>
<span class="text-ellipsis">
{{ value }}
</span>
</a-tooltip>
完整封装
<template>
<div class="table-ellipsis">
<span :ref="`text${id}${type}`" class="disNone">{{ value }}</span>
<span v-if="!isShowHover" class="text-ellipsis">
{{ value }}
</span>
<a-tooltip placement="topLeft" :title="value" v-else>
<span class="text-ellipsis">
{{ value }}
</span>
</a-tooltip>
</div>
</template>
<script>
export default {
name: 'TableEllipsis',
props: {
value: {
type: String,
default: '',
},
// 表格中不同的字段,同时需要做是否显示tooltip,用于区分
type: {
type: String,
default: '',
},
// 表格中多行显示,用id来区分不同组件
id: {
type: Number,
default: null,
},
},
data() {
return {
isShowHover: false,
}
},
mounted() {
this.getStyle()
},
methods: {
getStyle() {
const lineHeight =
getComputedStyle(this.$refs[`text${this.id}${this.type}`]).lineHeight.replace('px', '') - 0 || 20
const height = getComputedStyle(this.$refs[`text${this.id}${this.type}`]).height.replace('px', '') - 0
if (height > lineHeight * 1) {
this.isShowHover = true
} else {
this.isShowHover = false
}
},
},
}
</script>
<style lang="less" scoped>
.table-ellipsis {
position: relative;
.text-ellipsis {
max-width: 200px;
display: block;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.disNone {
position: absolute;
top: -10000px;
z-index: -1;
}
}
</style>