原创

vue2 组件:文本过长时显示省略号

基于 element ui

创建 text-ellipsis.vue 文件,内容如下:

<template>
  <el-tooltip
    effect="dark"
    :content="showText || placeholder"
    placement="top-start"
    class="tooltip"
    :open-delay="500"
    popper-class="text-ellipsis-tooltip-popper"
  >
    <div class="text" :style="textStyle">
      {{ showText || placeholder }}
    </div>
  </el-tooltip>
</template>
<script>
export default {
  name: 'text-ellipsis',
  props: {
    text: String,
    maxLength: Number,
    maxLine: {
      type: Number,
      default: 1
    },
    placeholder: {
      type: String,
      default: ''
    }
  },
  computed: {
    showText() {
      if (
        this.text
        && this.maxLength
        && this.text.length > this.maxLength
      ) {
        return this.text.substring(0, this.maxLength) + '...'
      } else
        return this.text
    },
    textStyle(){
      return {
        '-webkit-line-clamp': this.maxLine
      }
    }
  },
}
</script>
<style scoped lang="scss">
.text {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.text-ellipsis-tooltip-popper {
  max-width: 500px;
}
</style>

基于 ant design

创建 text-ellipsis.vue 文件,内容如下:

<template>
  <a-tooltip
    placement="topLeft"
    :title='showText || placeholder'
    :overlayStyle='titleStyle'
  >
    <span ref='text' :style='textStyle'>
      {{ showText || placeholder }}
    </span>
  </a-tooltip>
</template>
<script>
export default {
  name: 'text-ellipsis',
  props: {
    text: String,
    maxLength: Number,
    maxLine: {
      type: Number,
      default: 1
    },
    placeholder: {
      type: String,
      default: ''
    },
    titleMaxWidth: {
      type: Number,
      default: 250
    }
  },
  data(){
    return {
      // 文本框最大高度
      maxHeight: 0
    }
  },
  mounted() {
    // 计算文本框最大高度
    let textElement = this.$refs.text
    let textStyle = window.getComputedStyle(textElement)
    this.maxHeight = textStyle.lineHeight.split('px')[0] * this.maxLine
  },
  computed: {
    showText() {
      if (
        this.text
        && this.maxLength
        && this.text.length > this.maxLength
      ) {
        return this.text.substring(0, this.maxLength) + '...'
      } else
        return this.text
    },
    titleStyle(){
      return {
        'max-width': this.titleMaxWidth + 'px'
      }
    },
    textStyle(){
      return {
        display: '-webkit-box',
        WebkitBoxOrient: 'vertical',
        WebkitLineClamp: this.maxLine,
        overflow: 'hidden',
        '-webkit-line-clamp': this.maxLine,
        '-webkit-box-orient': 'vertical',
        textOverflow: 'ellipsis',
        maxHeight: this.maxHeight + 'px'
      }
    }
  }
}
</script>
正文到此结束