按行展示文本超过2行显示...展开更多/收起vue2.0(四)

<template>
  <div class="text-expand">
    <div class="text-content" :class="{ 'collapsed': isCollapsed }">
      <!-- <slot /> -->
      {{ textContent }}
    </div>
   <div class="flex justify-end">
    <button
    v-if="textFull.length > maxVisibleLines"
    @click="toggleCollapse"
    class="expand-btn"
  >
    {{ isCollapsed? '展开更多' : '收起' }}
  </button>
   </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';

export default {
  name: 'TextExpand',
  props: {
    maxVisibleLines: {
      type: Number,
      default: 1,
    },
    text: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    const textContent = ref(props.text);
    const isCollapsed = ref(true);
    const textFull = ref('');

    const toggleCollapse = () => {
      isCollapsed.value =!isCollapsed.value;
    };

    onMounted(() => {
      textFull.value = textContent.value;
      const lines = textFull.value.split('\n');
      if (lines.length <= props.maxVisibleLines) {
        isCollapsed.value = false;
      }

     //const visibleText = lines.slice(0, props.maxVisibleLines).join('\n');
      //textContent.value = visibleText;
      console.log(lines.length,props.maxVisibleLines)
    });

    return {
      textContent,
      isCollapsed,
      textFull,
      toggleCollapse,
    };
  },
};
</script>

<style scoped>
.text-content {
  display: -webkit-box;

}

.collapsed {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  transition: max-height 0.3s ease;
}

.expand-btn {
  margin-top: 5px;
}
</style>

 

posted @ 2024-12-16 14:35  Shimily  阅读(81)  评论(0)    收藏  举报