vue实现文字折叠
Vue 实现文字折叠功能
文字折叠功能通常用于长文本的展示与隐藏,以下是几种实现方式:
使用 v-show 或 v-if 控制显示
通过 Vue 的指令可以轻松实现文本的展开与折叠:
<template>
<div>
<p v-show="isExpanded">{{ longText }}</p>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
longText: '这里是很长的文本内容...'
}
}
}
</script>
使用 CSS 过渡效果
添加过渡效果使展开/收起更平滑:

<template>
<div>
<div class="text-container" :class="{ 'expanded': isExpanded }">
{{ longText }}
</div>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开' }}
</button>
</div>
</template>
<style>
.text-container {
max-height: 60px;
overflow: hidden;
transition: max-height 0.3s ease;
}
.text-container.expanded {
max-height: 1000px;
}
</style>
限制行数实现折叠
通过 CSS 控制显示行数:
<template>
<div>
<p :class="{ 'line-clamp': !isExpanded }">{{ longText }}</p>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开' }}
</button>
</div>
</template>
<style>
.line-clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>
使用第三方组件
对于更复杂的需求,可以考虑使用现成的 Vue 组件:

- vue-ellipsis
- vue-clamp
这些组件提供了更多自定义选项,如响应式折叠、多行控制等。
动态计算文本高度
对于需要精确控制的情况,可以动态计算文本高度:
<template>
<div>
<div ref="textElement" :style="{ height }">
{{ longText }}
</div>
<button @click="toggle">
{{ isExpanded ? '收起' : '展开' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
isExpanded: false,
longText: '...',
collapsedHeight: '60px',
expandedHeight: 'auto'
}
},
computed: {
height() {
return this.isExpanded ? this.expandedHeight : this.collapsedHeight
}
},
methods: {
toggle() {
this.isExpanded = !this.isExpanded
}
}
}
</script>
以上方法可以根据具体需求选择或组合使用,实现不同效果的文字折叠功能。






