vue之文本超出指定区域后显示省略号以及查看更多,点击查看更多显示全部

90 阅读1分钟

知识点:

  • 具名插槽
  • props传值
  • watch
  • scrollHeight:元素内容在垂直方向上的总高度,包括溢出的部分。如果元素没有溢出,则scrollHeight等于元素的clientHeight;常用于判断元素是否出现了滚动条,或者计算元素的实际高度以进行相关布局操作

**子组件:**textellipsisComponent.vue

<template>
  <div class="app">
    <span>
      <span class="limit-text">{{ text }}</span>
      <span class="more"><slot name="more"></slot></span>
      <slot name="after"></slot>
    </span>
  </div>
</template>

<script>
export default {
  inheritAttrs: false,
  props: {
    height: Number,
    text: String,
    isLimitHeight: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {};
  },
  watch: {
    text() {
      this.init();
    },
    isLimitHeight() {
      this.init();
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      let title = this.$el;
      let textDom = this.$el.querySelector(".limit-text");
      let more = this.$el.querySelector(".more");
      more.style.display = "none";
      this.$nextTick(() => {
        if (this.isLimitHeight) {
          if (title.scrollHeight > this.height) {
            more.style.display = "inline-block";
            let text = this.text;
            let n = 1000;
            while (title.scrollHeight > this.height && n > 0) {
              if (title.scrollHeight > this.height * 3) {
                textDom.innerText = text = text.substring(
                  0,
                  Math.floor(text.length / 2)
                );
              } else {
                textDom.innerText = text = text.substring(0, text.length - 1);
              }
              n--;
            }
          }
        } else {
          textDom.innerText = this.text;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app {
  text-align: left;
}
</style>

父组件:

<div class="desc">
    <textE
      :text="text"
      :height="70"
      style="width: 1200px"
      :isLimitHeight="isLimitHeight">
      <template slot="more">
          <span>...</span>
          <span class="link ellpies" @click="isLimitHeight = false">查看更多</span>
      </template>
      <span
       slot="after"
        class="link ellpies"
        v-if="!isLimitHeight"
        @click="isLimitHeight = true"
        >收起</span>
    </textE>
</div>

data() {
    return {
        isLimitHeight: true,
        text: '文本信息'
},


.ellpies {
  color: #0161d8;
  cursor: pointer;
}
.desc {
  margin-top: 15px;
  font-size: 14px;
  color: #333;
  text-indent: 2rem;
  padding-right: 40px;
  position: relative;
}

效果图:

GIF 2023-8-3 12-35-27.gif