【Element-UI】对el-tooltip进行二次封装,实现超出隐藏,鼠标移入显示(类似el-table的show-overflow-tooltip效果)

283 阅读1分钟

使用el-tooltip这个插件结合其自身的disabled属性,通过判断传入的内容所占宽度是否超出容器的宽度,来动态改变disabled,从而达到只有省略了的内容才会有hover,弹出tooltip显示全部的效果。

  1. 对el-tooltip进行二次封装,这里我的组件名叫做“omitTooltip”
<template>
  <div class="tooltip-container">
    <el-tooltip class="omit-tooltip" :disabled="showWhole" :content="text">
      <p ref="tooltipBox" class="text-box">
        <span ref="tooltipItem" class="">{{text}}</span>
      </p>
    </el-tooltip>
  </div>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      default: () => ""
    }
  },
  data(){
    return {
      showWhole: true
    }
  },
  watch:{
    text:{
      handler(){
        this.$nextTick(()=>this.checkWidth());
      },
      immediate: true
    }
  },
  methods:{
    checkWidth(){
      const boxWidth = this.$refs['tooltipBox'].offsetWidth;
      const itemWidth = this.$refs['tooltipItem'].offsetWidth;
      this.showWhole = boxWidth > itemWidth
    }
  }
};
</script>

<style scoped lang="less">
.tooltip-container{
    width:100%;
    .text-box{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}
</style>
  1. 使用该组件
<div class="test">
    <omit-tooltip :text="'超出部分显示省略号超出部分显示省略号'"></omit-tooltip>
</div>
<style>
.test{
    width:150px;
    height:20px;
    border:1px solid #345123;
    cursor:pointer;
}
</style>