vue3+ElementPlus+ts,文本超出元素宽度则显示省略号,并使用el-tooltip展示,不超出则不展示el-tooltip

根据元素内字数显示省略号和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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值