文字超出宽度,自动显示el-tooltip

604 阅读1分钟

“我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情

问题

在el-table中,如果使用show-overflow-tooltip,会发现,无法复制el-tooltip中的内容,直接在需要的列中加上el-tooltip,会使这一列没超出的也加上,没必要。所以自己封装一个text-tips组件

效果图:

image.png

具体代码

<template>
  <div class="text-tooltip">
    <el-tooltip
      popper-class="table-tooltip-padding0"
      :disabled="isShowTooltip"
      :effect="effect"
      :placement="placement"
    >
      <!-- 直接显示的内容 -->
      <p class="over-flow" :class="className" @mouseover="onMouseOver(refName)">
        <span :ref="refName" class="cursor">{{
          content === '' || content === null ? '--' : content
        }}</span>
      </p>
      <!-- tooltip中的内容 -->
      <div class="tooltip-content" slot="content">
        {{ content }}
      </div>
    </el-tooltip>
  </div>
</template>

根据传入的文字宽度,跟当前文字父元素的宽度做对比,如若超出的话则显示el-tooltip。 组件中可以传入 文字内容,className(可修改文字的宽度,样式) 以及tooltip的一些属性

  name: 'textTips',
  props: {
    // 显示的文字内容
    content: {
      type: [String, Number],
      default: () => {
        return ''
      }
    },
    // 外层框的样式,在传入的这个类名中设置文字显示的宽度
    className: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 为页面文字标识
    refName: {
      type: String,
      default: () => {
        return 'tooltipOver'
      }
    },
    placement: { type: String, default: 'top' },
    effect: { type: String, default: 'dark' },
  },
  data() {
    return {
      isShowTooltip: true
    }
  },
  methods: {
    onMouseOver(str) {
      let parentWidth = this.$refs[str]?.parentNode?.offsetWidth
      let contentWidth = this.$refs[str]?.offsetWidth
      // 判断是否开启tooltip功能
      if (contentWidth > parentWidth) {
        this.isShowTooltip = false
      } else {
        this.isShowTooltip = true
      }
    }
  }

注意在样式中,得给父元素设置不能换行。 改设tooltip内容的样式,这边写在了全局样式中,不太喜欢。

<style lang="less" scoped>
.over-flow {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
<style lang="less">
.table-tooltip-padding0 {
  padding: 0;
  .tooltip-content {
    max-height: 300px;
    overflow: auto;
    line-height: 20px;
    padding: 10px;
  }
}
</style>

使用:

    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        v-for="item in columns"
        :key="item.key"
        :label="item.title"
        :align="item.align ? item.align : 'center'"
        :width="item.width ? item.width : 'auto'"
      >
        <template slot-scope="{ row }">
          <text-tips :content="row[item.key]" refName="tooltipOver"></text-tips>
        </template>
      </el-table-column>
    </el-table>

这个组件,不单单可以用于表格,需要有这个效果的都可以使用。