SOURCE

<template>
  <el-tooltip :popper-class="`base-tooltip ${popperClass}`" :placement="placement" :disabled="isTooltip">
    <template #content>
      <div class="base-tooltip-content">
        <slot name="content" :content="content">{{ content }}</slot>
      </div>
    </template>
    <template v-if="auto" #default>
      <i class="is-auto-tips" :style="getStyle" ref="contentRef" @mouseenter="setIsTooltip">
        <slot>{{ content }}</slot>
      </i>
    </template>
    <template v-else #default>
      <slot>{{ content }}</slot>
    </template>
  </el-tooltip>
</template>

<script lang="ts">
import { defineComponent, toRefs, ref, computed, watch, nextTick, onMounted } from 'vue'

export default defineComponent({
  name: 'BaseToolTip',
  props: {
    // 是否自动计算显示tips
    auto: {
      type: Boolean,
      default: true,
    },
    // 最大显示行数
    rows: {
      type: Number,
      default: 100,
    },
    // 自定义样式类
    popperClass: {
      type: String,
      default: '',
    },
    // 位置
    placement: {
      type: String,
      default: 'top',
    },
    // 显示内容
    content: {
      type: String,
      default: '',
    },
    maxWidth: {
      type: String,
      default: '',
    },
  },
  setup(props, { slots }) {
    // 是否渲染为tooltip模式
    const isTooltip = ref(props.auto)

    const contentRef = ref(null)

    const getStyle = computed(() => {
      return {
        '-webkit-line-clamp': props.rows,
        'max-width': props.maxWidth
      }
    })

    const updateIsTooltip = (): void => {
      isTooltip.value = !(contentRef.value?.scrollHeight - contentRef.value?.offsetHeight > 1)
    }

    const setIsTooltip = async (): void => {
      // 自动计算状态下判断高度显示是否溢出,则显示为tooltip模式
      if (props.auto && props.content) {
        await nextTick()
        updateIsTooltip()
      }
    }

    onMounted(() => {
      setIsTooltip()
    })

    watch(
      () => props.auto,
      val => {
        isTooltip.value = val
      }
    )

    return {
      ...toRefs(props),
      isTooltip,
      contentRef,
      getStyle,
      setIsTooltip,
    }
  },
})
</script>

<style lang="scss">
.is-auto-tips {
  word-break: break-all;
  white-space: normal;
  font-style: normal;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}

.base-tooltip {
  max-width: 300px;
  line-height: 24px;
  word-break: break-all;
}
</style>
console 命令行工具 X clear

                    
>
console