ellipsisPopover.vue 1.13 KB
<template>
  <el-popover
    v-if="isTextLong"
    placement="top"
    popper-class="base-popper"
    trigger="hover"
    :content="content"
  >
    <span ref="textRef" slot="reference" class="line-ellipsis">{{ truncatedText }}</span>
  </el-popover>
  <span v-else>{{ content || '-' }}</span>
</template>

<script>
export default {
  name: 'EllipsisPopover',
  props: {
    content: {}
  },
  data() {
    return {
      maxWidth: 0
    }
  },
  computed: {
    truncatedText() {
      const maxLength = Math.ceil(this.maxWidth / 12);
      return this.content?.length > maxLength ? this.content.slice(0, maxLength) + '...' : this.content;
    },
    isTextLong() {
      const maxLength = Math.ceil(this.maxWidth / 12);
      return this.content?.length >= maxLength;
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.maxWidth = this.$refs.textRef?.getBoundingClientRect().width - 30 // 获取元素宽度
    })
  }
}
</script>

<style scoped>
.line-ellipsis {
  display: inline-block;
  width: 100%;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>