Vue查看全文实现
Vue 查看全文实现方法
在Vue中实现查看全文功能通常涉及文本截断和展开/折叠操作,以下是几种常见实现方式:
使用CSS控制文本显示
通过CSS的text-overflow和line-clamp属性实现基础文本截断:
<template>
<div>
<p :class="{ 'truncate': !isExpanded }">{{ longText }}</p>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开全文' }}
</button>
</div>
</template>
<style>
.truncate {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>
使用计算属性动态截断文本
对于更精确的字符控制,可以使用计算属性:
computed: {
truncatedText() {
return this.isExpanded
? this.longText
: this.longText.slice(0, 100) + '...';
}
}
第三方库实现
使用专门处理文本截断的库如vue-text-truncate:
import TextTruncate from 'vue-text-truncate'
export default {
components: { TextTruncate },
template: `
<text-truncate
:text="longText"
:lines="3"
less="收起"
more="展开全文"
/>
`
}
响应式高度检测
通过ref获取元素实际高度判断是否需要显示展开按钮:
methods: {
checkOverflow() {
const el = this.$refs.textElement
this.showToggle = el.scrollHeight > el.clientHeight
}
},
mounted() {
this.checkOverflow()
window.addEventListener('resize', this.checkOverflow)
}
动画过渡效果
为展开/收起添加平滑过渡:
.text-content {
transition: max-height 0.3s ease;
max-height: 60px;
overflow: hidden;
}
.text-content.expanded {
max-height: 1000px;
}
这些方法可根据具体需求组合使用,CSS方案性能最优但灵活性较低,计算属性方案适合精确控制字符数,第三方库方案实现最快捷但增加包体积。







