vue3自适应高度超出折叠功能
1. 需求
常有场景说看到内容如果出现多余一行或几行就出现折叠按钮,没有多就不用折现折叠按钮,点击折叠按钮可以展开或收起折叠内容。
2. 代码
<div class="tgd-box-cont1"><div :class="['tgd-box-cont1-left', isExpanded ? 'tgd-height-auto' : '']"ref="leftContent">...需要折叠的内容</div><div class="tgd-box-cont1-right"><el-buttonv-if="showToggle"@click="toggleExpand"size="mini"type=""class="tgd-box-btn1"link><span>{{ !isExpanded ? '展开' : '收起' }}</span><el-icon><CaretBottom v-if="!isExpanded" /><CaretTop v-else /></el-icon></el-button></div>
</div>
<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'const leftContent = ref(null)
const isExpanded = ref(false)
const showToggle = ref(false)function checkOverflow() {nextTick(() => {if (leftContent.value.scrollHeight > leftContent.value.clientHeight) {showToggle.value = true}})
}function toggleExpand() {isExpanded.value = !isExpanded.value
}// 当组件挂载后添加resize事件监听器
onMounted(() => {window.addEventListener('resize', handleResize)checkOverflow()
})// 当组件卸载前移除resize事件监听器,防止内存泄漏
onUnmounted(() => {window.removeEventListener('resize', handleResize)
})
</script>
<style lang="less" scoped>
.tgd-box-cont1 {padding-top: 16px;display: flex;align-items: stretch;justify-content: space-between;
}
.tgd-box-cont1-left {flex: 1;overflow: hidden;transition-duration: 0.5s;height: 73px;
}
.tgd-height-auto {height: auto;
}
.tgd-box-cont1-right {flex-basis: 119px;flex-shrink: 0;padding-top: 23px;text-align: right;.tgd-box-btn1 {padding: 0;font-size: 12px;width: auto;min-width: auto;& > span {margin-right: 8px;}}
}
</style>
3. 效果
求关注 |
---|
![]() |