当前位置:首页 > 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 文本溢出

纯 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>

响应式摘要长度

根据屏幕尺寸动态调整摘要长度:

vue实现摘要

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实现遮罩

vue实现遮罩

Vue 实现遮罩层的方法 在 Vue 中实现遮罩层可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-show 或 v-if 控制显示 通过 Vue 的指令动态控制遮罩层的显示与隐藏。…

vue slot实现

vue slot实现

vue slot 的实现方法 在 Vue 中,slot 是一种内容分发机制,允许父组件向子组件传递模板内容。以下是几种常见的 slot 实现方式: 默认 slot 默认 slot 是最基础的 slo…

vue实现CRUD

vue实现CRUD

Vue 实现 CRUD 操作 Vue 提供了响应式数据绑定和组件化开发能力,结合后端 API 可以轻松实现 CRUD(增删改查)功能。以下是基于 Vue 3 和 Axios 的完整实现方案。 安装依…

proxy实现vue

proxy实现vue

使用 Proxy 实现 Vue 响应式系统 Vue 3 的响应式系统基于 JavaScript 的 Proxy API,通过代理对象实现对属性的拦截和依赖追踪。以下是实现的核心逻辑: 创建响…

vue实现复制

vue实现复制

Vue 实现复制功能 在 Vue 中实现复制功能可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 Clipboard API Clipboard API 是现代浏览器提供的一种原生 AP…

vue实现vr

vue实现vr

Vue 实现 VR 的方法 Vue 可以与 WebVR 或 WebXR API 结合使用,通过 Three.js、A-Frame 等库实现 VR 效果。以下是几种常见方法: 使用 A-Frame 框…