天天看點

Vue 長文本元件(有展開更多按鈕)實作 附源碼及使用

原文位址:Vue 長文本元件(有展開更多按鈕) | Stars-One的雜貨小窩
最近項目需要優化長文本的顯示,如果長文本過長,固定顯示幾行并顯示一個展開更多的按鈕,點選按鈕即可把隐藏的文本顯示出來

稍微查了點資料,封裝了個元件,分享給大家

元件效果

Vue 長文本元件(有展開更多按鈕)實作 附源碼及使用
Vue 長文本元件(有展開更多按鈕)實作 附源碼及使用

元件代碼

<template>
  <div>
    <p ref="contentEl" :class="flag?'max-three-line':''">{{ `${content}` }}</p>
    <div v-if="!hideBtn" class="flex-row flex-center">
      <a class="text-blue" @click="flag = !flag">{{flag?'展開全部':'收起'}}</a>
    </div>
  </div>
</template>

<script>
  export default {
    name: "hasMoreDiv",
    props: {
      //内容文本
      content: {
        type: String,
        default: function () {
          return "";
        },
      },
    },
    data() {
      return {
        flag: false, //是否隐藏内容
        hideBtn: false
      };
    },
    mounted() {
      let el = this.$refs.contentEl
      let elHeight = el.offsetHeight
      //三行的高度為88.8
      this.hideBtn = elHeight <= 88.8
      //測量之後,修改flag,設定樣式
      this.flag = true
    },
    methods: {}

  }
</script>

<style scoped>
  .max-three-line {
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }
</style>
           

PS:目前設定是預設顯示3行,如果想修改,可以修改css屬性

-webkit-line-clamp

元件使用

使用import關鍵字導入元件,之後使用即可

import HasMoreDiv from 'xx.vue'
           

在頁面中使用,content即為要顯示的内容

<HasMoreDiv :content=""></HasMoreDiv>
           

提問之前,請先看提問須知

點選右側圖示發起提問

Vue 長文本元件(有展開更多按鈕)實作 附源碼及使用

或者加入QQ群一起學習

Vue 長文本元件(有展開更多按鈕)實作 附源碼及使用

TornadoFx學習交流群:1071184701

Vue 長文本元件(有展開更多按鈕)實作 附源碼及使用
vue