vue实现摘要
Vue 实现摘要的方法
在 Vue 中实现摘要功能可以通过多种方式,以下是一些常见的方法:
使用计算属性截取字符串
计算属性是 Vue 中处理数据逻辑的理想选择,可以动态截取字符串并添加省略号:
computed: {
summary() {
const maxLength = 100;
return this.fullText.length > maxLength
? this.fullText.substring(0, maxLength) + '...'
: this.fullText;
}
}
自定义过滤器
可以创建一个全局过滤器来处理文本摘要:
Vue.filter('summary', function(value, length) {
if (!value) return '';
return value.length > length
? value.substring(0, length) + '...'
: value;
});
模板中使用方式:
<p>{{ fullText | summary(100) }}</p>
使用 CSS 文本溢出
纯 CSS 方案适用于固定宽度的容器:
.summary {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
第三方库实现
对于更复杂的需求,可以使用专门处理文本截取的库,如 vue-truncate:
安装:
npm install vue-truncate
使用:
import Vue from 'vue'
import Truncate from 'vue-truncate'
Vue.use(Truncate)
模板中使用:
<truncate clamp="..." :length="100">{{ fullText }}</truncate>
实现交互式摘要
可以结合点击事件实现展开/收起功能:
data() {
return {
isExpanded: false,
fullText: '...完整文本...',
summaryLength: 100
}
},
computed: {
displayText() {
return this.isExpanded
? this.fullText
: this.fullText.substring(0, this.summaryLength) + '...';
}
}
模板部分:
<p>{{ displayText }}</p>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '展开' }}
</button>
响应式摘要长度
根据屏幕尺寸动态调整摘要长度:

computed: {
dynamicLength() {
return window.innerWidth < 768 ? 50 : 100;
},
summary() {
return this.fullText.length > this.dynamicLength
? this.fullText.substring(0, this.dynamicLength) + '...'
: this.fullText;
}
},
mounted() {
window.addEventListener('resize', this.handleResize);
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
}
这些方法可以根据具体需求选择使用,计算属性方案适合简单的截取需求,CSS 方案性能更好但灵活性较低,第三方库则提供了更多高级功能。






