vue实现摘要
Vue 实现摘要的方法
在Vue中实现摘要功能通常涉及文本截断、展开/收起交互等需求。以下是几种常见的实现方式:
使用CSS控制文本行数
通过CSS的-webkit-line-clamp属性可以轻松实现多行文本截断:
.truncate {
display: -webkit-box;
-webkit-line-clamp: 3; /* 控制显示行数 */
-webkit-box-orient: vertical;
overflow: hidden;
}
在Vue模板中应用:

<div :class="{ 'truncate': !isExpanded }">{{ longText }}</div>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开' }}
</button>
使用计算属性动态截取文本
对于需要精确控制字符数的场景:
computed: {
summary() {
return this.isExpanded
? this.fullText
: this.fullText.slice(0, 100) + '...';
}
}
使用第三方库
vue-truncate-collapsed等专门库提供更丰富的功能:

import { Truncate } from 'vue-truncate-collapsed';
export default {
components: { Truncate },
template: `
<truncate
:length="100"
:text="longText"
ellipsis="..."
expandText="更多"
/>
`
}
响应式摘要
根据容器宽度自动调整摘要长度:
methods: {
updateSummary() {
const containerWidth = this.$refs.container.offsetWidth;
this.displayText = this.calculateOptimalText(containerWidth);
}
},
mounted() {
window.addEventListener('resize', this.updateSummary);
this.updateSummary();
}
带富文本的摘要处理
处理包含HTML标签的内容时:
computed: {
plainText() {
return this.richText.replace(/<[^>]+>/g, '');
},
safeSummary() {
const text = this.isExpanded ? this.plainText : this.plainText.substring(0, 150);
return text + (this.isExpanded ? '' : '...');
}
}
每种方法适用于不同场景,CSS方案适合纯UI展示,计算属性适合简单逻辑,第三方库适合复杂交互需求,响应式方案适合自适应布局,富文本处理则针对包含格式的内容。






