vue实现多行展开收起

故事背景: 产品在移动端提出文本超过 4 行需要...显示并且支持点击按钮展开, 实现起来其实还是比较简单的, 但是怎么把代码写的最优雅呢, 今天把自己的实现方案贴出来供大家参考

<template>
  <div>
    <p class="line-clamp">{{ content }}</p>
    <i v-if="showBtn" @click="handleUpdateStyle"> {{ unflod ? '展开更多>>>' : '收起' }}</i>
  </div>
</template>

<script>
export default {
  props: ['content'],
  data() {
    return {
      showBtn: false,
      unflod: true
    }
  },
  async mounted() {
   await this.$nextTick()
   const { scrollHeight, offsetHeight } = this.$el.querySelector('p')
   if (scrollHeight > offsetHeight) {
    this.showBtn = true
   }
  },
  methods: {
    handleUpdateStyle() {
      const hasAttr = this.$el.querySelector('p')?.getAttribute?.('class')?.includes('line-clamp')
      this.$el.querySelector('p')?.classList[hasAttr ? 'remove' : 'add']('line-clamp')
      this.unflod = !hasAttr
    }
  }
}
</script>

<style lang="scss" scoped>
  .line-clamp {
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
    overflow: hidden;
    word-break: break-all;
  }
  i {
    color: #3e98ff;
  }
</style>>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容