element之自定义表格超出显示省略号并显示文字提示(tooltip)

1. 背景

在一次后台列表开发中,由于表格字段没多少,所以把备注字段也在表格展示了出来,但是因为备注字数较大,所以给 el-table-column 添加了 show-overflow-tooltip 属性。但是,由于备注真的很长,所以显示的文字提示横向占了整个窗口,😱😱天哪,这也太难看了,于是想到了使用 sass 去控制长度,就这样解决了。
但是,需求往往没有这么简单😶😶,又要求显示的字体提示要保留一定的格式,如换行。那这…没办法,只能自己写组件了。

2. 代码

<template>
  <div class="tipContainer"
       ref="tipContainer">
    <el-tooltip
      :disabled="!enableTip"
      ref="tooltip"
      class="item"
      :effect="effect"
      :placement="placement"
      v-bind="$attrs">
      <div class="table-tooltip-tip" slot="content">{{ value }}</div>
      <span
        class="table-tooltip-content"
        ref="tooltipContent"
        v-if="noSlot"
        :class="{'ellipsis': enableTip}">{{ value }}</span>
      <slot v-else></slot>
    </el-tooltip>
  </div>
</template>

<script>
export default {
  name: "TableTooltip",
  props: {
    // 始终保持提示tip
    tipKeep: Boolean,
    // 内容
    value: String,
    // 提示位置
    placement: {
      type: String,
      default: 'top'
    },
    // 提示主题
    effect: {
      type: String,
      default: 'dark'
    }
  },
  data() {
    return {
      enableTip: false
    }
  },
  computed: {
    noSlot() {
      // 判断有没有插槽(默认插槽除外)
      return !this.$slots.default;
    }
  },
  mounted() {
  	// 比较文字提示组件与父级宽度,用于判断要不要启用文字提示与显示省略号
    if (this.$refs.tipContainer && this.$refs.tooltipContent) {
      const tipWidth = this.$refs.tipContainer.offsetWidth;
      const tipContentWidth = this.$refs.tooltipContent.offsetWidth;
      this.enableTip = tipWidth < tipContentWidth;
    }
  }
}
</script>

<style lang="scss" scoped>
.tipContainer {
  overflow: hidden;
  width: 100%;
}

.table-tooltip-tip {
  max-width: 600px;
  white-space: pre-wrap;
}

.table-tooltip-content {
  white-space: nowrap;

  &.ellipsis {
    display: block;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
  }
}
</style>

3. 原理

重新封装了 elementui 的 Tooltip 文字提示组件,通过比较文字提示组件宽度与父级的宽度,来启用提示与显示省略号,然后利用 white-space: pre-wrap; 来格式化文字提示内容。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会功夫的李白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值