当前位置:首页 > VUE

vue实现摘要

2026-03-06 22:44:09VUE

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 文本溢出

vue实现摘要

纯 CSS 方案适用于固定宽度的容器:

.summary {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

第三方库实现

对于更复杂的需求,可以使用专门处理文本截取的库,如 vue-truncate

安装:

vue实现摘要

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 方案性能更好但灵活性较低,第三方库则提供了更多高级功能。

标签: 摘要vue
分享给朋友:

相关文章

vue 实现loading

vue 实现loading

Vue 实现 Loading 的方法 使用 v-if 和 v-show 控制显示 在 Vue 中可以通过 v-if 或 v-show 控制 loading 组件的显示与隐藏。v-if 会动态创建或销毁…

vue 实现协同

vue 实现协同

Vue 实现协同编辑的方案 协同编辑指多个用户同时编辑同一文档并实时同步更改。Vue 结合相关库和技术可轻松实现该功能。 使用 WebSocket 实现实时通信 WebSocket 提供全双工通信,…

vue实现treetable

vue实现treetable

Vue实现TreeTable的方法 使用第三方组件库(如Element UI) Element UI的el-table组件支持树形表格展示,通过设置row-key和tree-props属性即可实现。…

vue 实现文字滚动

vue 实现文字滚动

Vue 实现文字滚动效果 使用CSS动画实现 通过CSS的@keyframes和transform属性实现文字滚动效果: <template> <div class="scro…

vue实现滚动监听

vue实现滚动监听

滚动监听的基本实现 在Vue中实现滚动监听可以通过原生JavaScript的window.addEventListener或结合Vue的生命周期钩子完成。以下是一个基础示例: export defa…

vue 实现页面返回

vue 实现页面返回

实现页面返回的方法 在Vue中实现页面返回功能可以通过多种方式实现,以下是几种常见的方案: 使用Vue Router的go方法 通过Vue Router的go方法可以控制浏览器的历史记录导航。rou…