基于element-ui 制作省略显示组件 支持多行

570 阅读1分钟
<template>
  <div ref="el-ellipsis-display" class="el-ellipsis-display">
    <el-popover
      placement="top-start"
      trigger="hover"
      popper-class="more-popper"
      :disabled="isPopoverShow || !showPop"
      :content="content"
    >
      <div slot="reference">
        <div :class="isMore ? [] : ['multi-ellipsis--l' + limit]" :style="{ maxWidth: maxWidth, lineHeight: `${lineHeight}px` }" @mouseenter="showPopover">
          <span ref="heightView">{{ content }}</span>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script>
export default {
  name: 'ElEllipsisDisplay',
  props: {
    // popover 最大宽度
    maxWidth: {
      type: String,
      default: () => '100%'
    },
    // 展示内容
    content: {
      type: String,
      default: () => ''
    },
    // 行高 用来计算是否是省略显示
    lineHeight: {
      type: Number,
      default: () => 34
    },
    // 默认展示几行
    limit: {
      type: Number,
      default: () => 1
    },
    // 是否展示popover
    showPop: {
      type: Boolean,
      default: () => true
    }
  },
  data() {
    return {
      isPopoverShow: false,
      isMore: false,
      isOverHeight: false
    }
  },
  watch: {
    content: function() {
      this.$nextTick(() => {
        this.computeOverHeight()
      })
    }
  },
  mounted() {
    this.computeOverHeight()
  },
  methods: {
    computeOverHeight() {
      this.isOverHeight = this.$refs.heightView.offsetHeight > (this.lineHeight * this.limit)
    },
    showPopover() {
      this.computeOverHeight()
      if (this.isOverHeight && !this.isMore) {
        this.isPopoverShow = false
      } else {
        this.$nextTick(() => {
          this.isPopoverShow = true
        })
      }
    }
  }
}
</script>
<style scoped lang="scss">
@for $i from 1 through 1000 {
  .multi-ellipsis--l#{$i} {
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: #{$i};

    /* autoprefixer: ignore next */
    -webkit-box-orient: vertical;
    span {
      word-wrap: break-word;
      white-space: normal;
    }
  }
}
</style>

参考资料: elementui.jujiaotech.com/#/zh-CN/com…