背景

在实际项目中使用el-table表格时单元格内容超出一行时需要实现溢出显示...同时悬浮提示,可以调用show-overflow-tooltip属性设为true即可。大多时候在非表格中的一般文字标签溢出时也需要省略号同时悬浮提示的效果,而ElementUI组件库中的el-tooltip并不能灵活的根据是否有省略号实现该效果。

解决方案

  • 描述
    实现文字溢出省略悬浮提示的效果最快的方式是基于el-tooltip进行二次开发,但是直接使用el-tooltip不管文字是否溢出都有悬浮提示效果,因此需要判断文字是否溢出然后动态的添加el-tooltip进行悬浮提示。
  • 关键代码
   // el dom元素
  textRange (el) {
  const textContent = el
  const targetW = textContent.getBoundingClientRect().width
  const range = document.createRange()
  range.setStart(textContent, 0)
  range.setEnd(textContent, textContent.childNodes.length)
  const rangeWidth = range.getBoundingClientRect().width
  return rangeWidth > targetW
},

该方法可以用于判断文字是否有溢出,如果溢出返回tur,否则返回false

实现代码

<template>
  <div style="display:inline-block;position:relative;"  @click="handleClick">
      <div @mouseenter="(e) => isShowToltip(e)" @mouseout="hideTip()" v-if="!isShow" class="text" ref="tooltip">{{text}}
      </div>
      <el-tooltip v-if="isShow" class="item" effect="dark" :content="text" placement="top-start">
        <div class="text">{{text}}</div>
      </el-tooltip>
      <div class="slot-class" v-if="isShow">
        <slot></slot>
      </div>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
    }
  },
  props:{
      text:{
        type:String,
        default:''
      },
      isShow:{
        type:Boolean,
        default:false
      }
  },
  methods: {
    isShowToltip (e) {
      const bool = this.textRange(e.target)
      console.log(bool)
      this.isShow= bool
      this.$forceUpdate()
    },
    hideTip () {
      this.isShow = false
      this.$forceUpdate()
    },
    // el dom元素
  textRange (el) {
  const textContent = el
  const targetW = textContent.getBoundingClientRect().width
  const range = document.createRange()
  range.setStart(textContent, 0)
  range.setEnd(textContent, textContent.childNodes.length)
  const rangeWidth = range.getBoundingClientRect().width
  return rangeWidth > targetW
},
handleClick(){
   this.$emit('tooptipClick')
},

  },
  mounted(){
    this.isShow=this.textRange(this.$refs.tooltip)
    console.log(this.isShow)
  },
  beforeDestroy(){
    this.isShow=false
  },
  updated(){
    this.isShow=this.textRange(this.$refs.tooltip)
  },
  watch:{
    isShow(val){
     console.log(val)
    }
  }
}
</script>

<style scoped>
.text{
  width: 300px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow:ellipsis;
}
.slot-class{
  position: absolute;
  right: -20px;
  top: 2px;
  display: inline-block;
}
</style>

使用

  • 引入组件
import myText form '......'
  • 注册组件
components:{
   myText
}
  • 引用标签
 <my-tooltip :text="item.serialNo+'-'+item.name +'('+item.itemCount+')'" v-if="loadTooltip" :isShow="isShow">
 <slot>({{item.itemCount}})</slot>
 </my-tooltip>

text属性是要显示的文字,isShow用于控制悬浮标签显示

最后修改:2022 年 10 月 25 日
如果觉得我的文章对你有用,请随意赞赏