vue实现信息删减
Vue 实现信息删减的方法
使用计算属性动态截取文本
通过计算属性结合字符串的 slice 或 substring 方法实现文本截取,适合需要响应式更新的场景:
computed: {
truncatedText() {
return this.fullText.length > 50
? this.fullText.substring(0, 50) + '...'
: this.fullText;
}
}
模板中直接使用:
<p>{{ truncatedText }}</p>
自定义过滤器/管道
Vue 2.x 可使用过滤器,Vue 3.x 可使用全局属性或组合式函数:
Vue 2 示例:

filters: {
truncate(value, length) {
return value.length > length
? value.slice(0, length) + '...'
: value;
}
}
使用方式:
<p>{{ fullText | truncate(30) }}</p>
使用 CSS 文本溢出控制
纯视觉层面的截断,不影响原始数据:

.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
组件化封装
创建可复用的截断组件,支持动态配置:
<template>
<span :title="showFull ? '' : text">
{{ showFull ? text : truncatedText }}
<button @click="toggle"> {{ showFull ? '收起' : '展开' }} </button>
</span>
</template>
<script>
export default {
props: ['text', 'maxLength'],
data() {
return { showFull: false }
},
computed: {
truncatedText() {
return this.text.slice(0, this.maxLength) + '...';
}
},
methods: {
toggle() {
this.showFull = !this.showFull;
}
}
}
</script>
第三方库
使用专门处理文本截断的库如 vue-text-truncate:
import TextTruncate from 'vue-text-truncate';
components: { TextTruncate }
模板使用:
<text-truncate
:text="longText"
:max-chars="100"
ellipsis="..."
/>
注意事项
- 性能敏感场景避免在计算属性中进行复杂计算
- 需要精确字符计算时注意中英文字符差异
- 移动端显示需考虑不同屏幕尺寸的动态截断长度
- 可访问性需求应保留完整文本的
title或aria-label属性






