基于Element-plus封装多行文字溢出显示tooltip组件

867 阅读1分钟

组件功能

可以根据文字是否溢出来动态展示el-tooltip组件,支持多行文字溢出

<script setup lang="ts">
import { ref } from 'vue';

interface Props {
  text: string//文字
  row?:number, //文字行数
  textWidth?: string//文字宽度
  isHtmlText?:boolean//是否传入html
}

const props = withDefaults(defineProps<Props>(), {
    text: '',
    row: 1,
    textWidth: '100%',
    isHtmlText: false
});

const tooltipFlag = ref(false);

const visibilityChange = (event :any) => {
    if (event.target.scrollHeight > event.target.clientHeight) {
            tooltipFlag.value = true;
    } else {
            tooltipFlag.value = false;
    }
};

</script>
<template>
  <el-tooltip
    ref="tlp"
    effect="dark"
    :disabled="!tooltipFlag"
    class="tooltip"
    v-bind="$attrs"
  >
    <div
      @mouseenter="visibilityChange($event)"
      class="tooltip-wrap"
      :style="{ width: props.textWidth }"
      >
        <div v-html="text" v-if="isHtmlText"></div>
        <div v-else>{{text}}</div>
      </div
    >
  </el-tooltip>
</template>


<style scoped >

.tooltip-wrap {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: v-bind(row);

}
</style>

组件使用

  • text:展示的文字
  • row:显示文字行数
  • textWidth:文字宽度
  • isHtmlText:传入的文字是否是html字符串
  • 利用 v-bind="$attrs"特性绑定el-tooltip属性(如:show-after,raw-content)
  	<ellipsis-tooltip
            :text='record.extraContent'
            :row="2"
            :show-after="500"
            :content="record.extraContent"
            raw-content
            :isHtmlText="true"
     />

最终效果

20220824-174225.gif