通过文本长度判断是都展开收起vue3.0(二)
<template> <div class="text-container"> <p v-if="isCollapsed" :title="fullText">{{ trimmedText }}</p> <p v-else>{{ fullText }}</p> <div class="flex justify-end"><button @click="toggleText">{{ isCollapsed? '展开' : '收起' }}</button></div> </div> </template> <script setup lang="ts"> import { ref, onMounted, onUnmounted,computed } from 'vue'; const props = defineProps({ // 完整的文本内容 text: { type: String, required: true }, // 初始时是否展开,默认为 false(收起状态) initialExpanded: { type: Boolean, default: false }, // 收起时显示的最大字符数,默认为 100 maxLength: { type: Number, default: 100 } }) const isCollapsed = ref(!props.initialExpanded) const fullText = ref(props.text) const trimmedText = computed(() => { if (fullText.value.length <= props.maxLength) { return fullText.value } else { return fullText.value.slice(0, props.maxLength) + '...' } }) const toggleText = () => { isCollapsed.value =!isCollapsed.value } </script> <style scoped> .text-container { white-space: pre-line; } </style>
<ExpandableText :text="longText" :maxLength="150" :initialExpanded="false" />
import ExpandableText from '@/components/ExpandableText.vue';
给心灵一个纯净空间,让思想,情感,飞扬!