uni-qnc-tob/src/components/LExpandCollapse.vue

62 lines
1.4 KiB
Vue
Raw Normal View History

2024-11-24 15:21:01 +08:00
<script setup>
import { computed, ref, useSlots } from 'vue'
// 接收最大长度的 prop默认值 100
const props = defineProps({
maxLength: {
type: Number,
default: 100,
},
})
// 记录当前是否展开
const isExpanded = ref(false)
// 获取 slot 内容
const slots = useSlots()
// 计算截断后的内容
const truncatedContent = computed(() => {
const slotContent = getSlotContent()
return slotContent.length > props.maxLength
? `${slotContent.slice(0, props.maxLength)}...`
: slotContent
})
// 获取 slot 内容,确保返回的内容为字符串
function getSlotContent() {
const slotVNode = slots.default ? slots.default()[0] : null
return slotVNode ? slotVNode.children.toString().trim() : '' // 获取并转化为字符串
}
// 切换展开/收起状态
function toggleExpand() {
isExpanded.value = !isExpanded.value
}
</script>
<template>
<view>
<!-- 展开/收起按钮 -->
<!-- 展开/收起的内容 -->
<text v-if="isExpanded">
<slot /> <!-- 使用 slot 来展示传递的内容 -->
</text>
<text v-else>
<text>{{ truncatedContent }}</text>
</text>
<text
:title="isExpanded ? '点击收起' : '点击展开'"
class="cursor-pointer text-blue-500"
@click="toggleExpand"
>
{{ isExpanded ? '收起' : '展开' }}
</text>
</view>
</template>
<style scoped>
</style>