基于el-tooltip组件封装超出显示省略号,鼠标hover显示tooltip的组件

基于el-tooltip组件封装超出显示省略号,鼠标hover显示tooltip的组件

el-tooltip组件存在的问题:

  • el-tooltip没有行超出显示省略号的功能
  • 使用了该组件每个hover都会显示tooltip,没有满足超出才显示的需求。

基于el-tooltip组件,实现一个超出行才显示hover tip的组件

<template>
  <el-tooltip :disabled="!isShow" v-bind="$attrs">
    <template #content>
      <slot name="content">{{ props.content }}</slot>
    </template>
    <div class="content" :style="{width: props.width}" @mouseover="showTooltip">
   <span ref="contentRef">
     <slot>{{ props.content }}</slot>
   </span>
    </div>
  </el-tooltip>
</template>

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

interface props {
  content: string;
  width: string;
}

const props = withDefaults(defineProps<props>(), {
  content: "",
  width: "",
});

const isShow = ref(true);
const contentRef = ref();
const showTooltip = () => {
  //  判断行元素width是否超过父元素width,超过才显示el-tooltip
  if (contentRef.value?.parentNode.offsetWidth < contentRef.value?.offsetWidth) {
    isShow.value = true;
  } else {
    isShow.value = false;
  }
};
</script>

<style scoped>
.content {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>

效果
请添加图片描述


参考:https://juejin.cn/post/7011037199411970056