标题文字,超出显示...,并且 el-tooltip 提示

81 阅读1分钟

效果

upload_fba95d256d8a8ae0536a4de0f2f9cfa9.png

根据固定宽度实现

<template>
  <div class="item-header">
    <el-tooltip effect="dark" :content="item.name" :disabled="item.name | showTooltip(339)" placement="top">
      <h3>{{ item.name }}</h3>
    </el-tooltip>
    <el-button type="text">在线办理</el-button>
  </div>
</template>

<script>
export default {
  filters: {
    // 定义过滤器来计算文字宽度,然后跟实际 dom 宽度对比
    showTooltip(msg, width) {
      let app = document.querySelector('#app')
      let span = document.createElement('span')
      span.innerHTML = msg
      app.appendChild(span)
      let isShow = span.offsetWidth >= width
      app.removeChild(span)
      return !isShow
    },
  },
}
</script>

<style lang="scss" scoped>
.item-header {
  display: flex;
  align-items: center;
  position: relative;

  &::before {
    display: block;
    content: '';
    position: absolute;
    left: -14px;
    top: 6px;
    width: 8px;
    height: 8px;
    background-color: #4974f5;
    border-radius: 50%;
  }

  h3 {
    flex: 1;
    color: #262626;
    font-weight: 600;
    font-size: 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .sp-button {
    margin-left: 20px;
    min-height: 18px;
    line-height: 18px;
    padding: 0;
  }
}
</style>

定义过滤器来计算文字宽度,然后跟实际 dom 宽度对比(建议实际 dom 宽度 + 1px)。

自动计算宽度实现

<template>
  <div v-if="data" ref="moreRef" class="more-content" :style="{ 'max-height': lineNum * 18 + 'px' }">
    {{ data }}
    <div v-if="isMore" class="more-wrapper">
      <span>...</span>
      <el-popover title="" width="366" trigger="click" :content="data" placement="left">
        <span slot="reference" class="btn-more">「更多」</span>
      </el-popover>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    data: { type: String, required: true },
    lineNum: { type: Number, default: 2 },
  },
  data() {
    return {
      isMore: false,
    }
  },
  mounted() {
    const moreRef = this.$refs.moreRef
    moreRef && (this.isMore = moreRef.scrollHeight > moreRef.clientHeight) // 判断内容高度是否大于实际高度,是则表示要显示更多
  },
}
</script>

<style lang="scss" scoped>
.more-content {
  position: relative;
  margin-right: 70px;
  margin-top: 6px;
  font-size: 12px;
  color: #8c8c8c;
  line-height: 18px;
  overflow: hidden;
  .more-wrapper {
    position: absolute;
    right: 0;
    bottom: 0;
    padding-left: 16px;
    background: linear-gradient(91deg, transparent 0, #fff 20%);
    .btn-more {
      color: #4974f5;
    }
  }
}
</style>