vue实现文本折叠
实现文本折叠的基本思路
文本折叠功能通常涉及控制文本的显示高度,超出指定行数后显示“展开/收起”按钮。Vue中可以通过动态绑定CSS样式和条件渲染实现这一效果。
使用CSS控制文本行数
通过CSS的-webkit-line-clamp属性限制文本显示行数,结合overflow: hidden实现折叠效果:
<template>
<div>
<div
:class="{'text-collapse': isCollapsed}"
ref="content"
>
{{ longText }}
</div>
<button @click="toggleCollapse">
{{ isCollapsed ? '展开' : '收起' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
longText: '这里是需要折叠的长文本内容...',
isCollapsed: true
}
},
methods: {
toggleCollapse() {
this.isCollapsed = !this.isCollapsed
}
}
}
</script>
<style>
.text-collapse {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>
动态计算是否需要折叠
对于不确定长度的文本,可通过计算文本高度决定是否需要显示折叠按钮:
<template>
<div>
<div
:style="{ height: isCollapsed ? maxHeight + 'px' : 'auto' }"
ref="content"
class="content"
>
{{ longText }}
</div>
<button
v-if="showToggle"
@click="toggleCollapse"
>
{{ isCollapsed ? '展开' : '收起' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
longText: '长文本内容...',
isCollapsed: true,
showToggle: false,
maxHeight: 60
}
},
mounted() {
this.checkOverflow()
},
methods: {
toggleCollapse() {
this.isCollapsed = !this.isCollapsed
},
checkOverflow() {
const el = this.$refs.content
this.showToggle = el.scrollHeight > el.clientHeight
}
}
}
</script>
<style>
.content {
overflow: hidden;
transition: height 0.3s ease;
}
</style>
使用第三方库
对于更复杂的需求,可以考虑使用专门处理文本折叠的Vue组件库:

-
vue-text-collapse
安装:npm install vue-text-collapse
使用示例:<template> <text-collapse :text="longText" :length="100" /> </template> -
clamp.js
通过指令方式实现:
import clamp from 'clamp-js' export default { directives: { clamp: { inserted(el, binding) { clamp(el, { clamp: binding.value || 3 }) } } } }模板中使用:
<div v-clamp>长文本内容...</div>
动画过渡效果
为折叠/展开添加平滑动画:
<template>
<div>
<div
class="content"
:style="{ maxHeight: isCollapsed ? '60px' : 'none' }"
>
{{ longText }}
</div>
<button @click="toggleCollapse">
{{ isCollapsed ? '展开' : '收起' }}
</button>
</div>
</template>
<style>
.content {
overflow: hidden;
transition: max-height 0.5s ease;
}
</style>
多行文本省略方案
纯CSS实现多行省略(兼容性方案):
.ellipsis {
position: relative;
line-height: 1.4em;
max-height: 4.2em; /* 3行 */
overflow: hidden;
}
.ellipsis::after {
content: '...';
position: absolute;
right: 0;
bottom: 0;
background: white;
padding: 0 5px;
}






