根据元素内字数显示省略号和el-tooltip虽然方便,但是很多情况下不太美观,故记录一下个人在用的封装的根据根据元素宽度判断需不需要省略显示
主要代码:
<template>
<el-tooltip
effect="dark"
:content="props.tooltipContent ? props.tooltipContent : props.content"
placement="top"
:disabled="isShow"
>
<template #content>
<!-- 此处的默认值先看tooltipContent有没有,没有就给默认content -->
<div style="max-width: 150px" name="tooltipContent">
{{ props.tooltipContent ? props.tooltipContent : props.content }}
</div>
</template>
<div
:class="toolTipStyle"
:style="{ width: props.width, textAlign: props.textAlign }"
@mouseover="isShowTooltip"
>
<span ref="contentRef">
<!-- 给一个没有写插槽的默认值,兼容纯文本的情况 -->
<slot name="content">{{ props.content || '-' }}</slot>
</span>
</div>
</el-tooltip>
</template>
<script setup lang="ts">
import { ref } from 'vue'
// 定义props的类型
interface props {
// 传入的文本内容
content?: string
// 父元素宽度
width?: string
// tooltip展示的内容,传则显示传入的,不传默认显示props.content传入的
tooltipContent?: string
// 文本居中或者居左或者居右展示,默认左
textAlign?: any
// 传'content'则单行超出省略,传'clamp'则超出2行省略
toolTipStyle?: string
}
// 使用withDefaults来给props赋默认值
const props = withDefaults(defineProps<props>(), {
content: '',
width: '',
tooltipContent: '',
textAlign: 'left',
toolTipStyle: 'content',
})
// 使用isShow来控制tooltip是否显示
let isShow = ref<boolean>(true)
// 在span标签上定义一个ref
const contentRef = ref()
const isShowTooltip = function (): void {
// 计算span标签的offsetWidth与盒子元素的offsetWidth,给isShow赋值
if (props.toolTipStyle == 'content') {
if (
contentRef.value.parentNode.offsetWidth >= contentRef.value.offsetWidth
) {
isShow.value = true
} else {
isShow.value = false
}
}
if (props.toolTipStyle == 'clamp') {
if (
contentRef.value.parentNode.offsetHeight > contentRef.value.offsetHeight
) {
isShow.value = true
} else {
isShow.value = false
}
}
}
</script>
<style>
// 单行省略
.content {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
// 超出2行省略
.clamp {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
父组件引用:
<template>
<div>
<EllipsisTip :content="row.bankAccountName" width="100%" />
</div>
<div>
<EllipsisTip :content="row.bankAccountName" textAlign="center" />
</div>
</template>