ellipsisText.vue 2.04 KB
<template>
  <el-popover
    placement="top"
    trigger="hover"
    :content="finalPopoverContent"
    :disabled="!isOverflow"
    width="400"
  >
    <span
      ref="text"
      slot="reference"
      class="ellipsis"
      @mouseenter="checkOverflow"
    >
      <slot>
        {{ content || '--' }}
      </slot>
    </span>
  </el-popover>
</template>

<script>
export default {
  name: 'EllipsisText',
  props: {
    content: [String, Number],
    popoverContent: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isOverflow: false
    };
  },
  computed: {
    finalPopoverContent() {
      if (this.popoverContent) return this.popoverContent;
      if (this.$slots.default) {
        return this.$slots.default[0].text || this.content || '--';
      }
      return this.content || '--';
    }
  },
  methods: {
    checkOverflow() {
      const el = this.$refs.text;
      if (el) {
        this.isOverflow = el.scrollWidth > el.clientWidth;
      }
    }
  },
  mounted() {
    this.checkOverflow();
  },
  watch: {
    content() {
      this.$nextTick(this.checkOverflow);
    },
    '$slots.default': {
      handler() {
        this.$nextTick(this.checkOverflow);
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.dark-popover {
  background-color: #333 !important;   /* 深色背景 */
  color: #fff !important;              /* 白色文字 */
  border-color: #333 !important;       /* 边框与背景同色 */
  max-width: 300px !important;         /* 设置最大宽度,可按需调整 */
  word-wrap: break-word;                /* 长单词换行 */
  font-size: 14px;                      /* 调整字体大小(可选) */
  line-height: 1.5;                     /* 调整行高(可选) */
}
.dark-popover .popper__arrow,
.dark-popover .popper__arrow::after {
  border-top-color: #333 !important;    /* 箭头颜色(根据 placement 调整方向) */
}
.ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
</style>