当前位置:首页 > VUE

vue实现文本折叠

2026-02-17 16:36:16VUE

实现文本折叠的基本思路

在Vue中实现文本折叠功能,通常需要控制文本的显示高度,通过"展开/收起"按钮切换状态。核心是结合CSS的max-heightoverflow属性,配合Vue的数据绑定。

基础实现方法

模板部分

<template>
  <div>
    <div 
      class="text-content" 
      :class="{ 'collapsed': isCollapsed }"
      ref="content"
    >
      {{ longText }}
    </div>
    <button @click="toggleCollapse">
      {{ isCollapsed ? '展开' : '收起' }}
    </button>
  </div>
</template>

样式部分

.text-content {
  overflow: hidden;
  transition: max-height 0.3s ease;
}

.collapsed {
  max-height: 60px; /* 折叠后的高度 */
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 显示行数 */
  -webkit-box-orient: vertical;
}

脚本部分

export default {
  data() {
    return {
      isCollapsed: true,
      longText: '这里是很长的文本内容...'
    }
  },
  methods: {
    toggleCollapse() {
      this.isCollapsed = !this.isCollapsed
    }
  }
}

动态计算折叠高度

对于动态内容,可以使用clientHeight获取实际高度:

export default {
  mounted() {
    this.contentHeight = this.$refs.content.clientHeight
  },
  data() {
    return {
      contentHeight: 0,
      isCollapsed: true
    }
  }
}

更新CSS部分:

.collapsed {
  max-height: 60px;
}

使用第三方库

对于更复杂的需求,可以考虑使用vue-text-collapse等专门库:

安装:

npm install vue-text-collapse

使用:

<template>
  <text-collapse 
    :text="longText" 
    :length="100"
  />
</template>

<script>
import TextCollapse from 'vue-text-collapse'
export default {
  components: { TextCollapse }
}
</script>

多行文本省略方案

纯CSS实现多行省略(兼容性较好方案):

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

动画效果增强

添加平滑的展开/收起动画:

vue实现文本折叠

.text-content {
  transition: max-height 0.5s ease-in-out;
}

通过调整max-height的值实现动画效果,注意设置足够大的最终高度值。

标签: 文本vue
分享给朋友:

相关文章

vue实现节流

vue实现节流

vue实现节流的方法 在Vue中实现节流(throttle)功能,通常用于限制高频事件的触发频率,例如滚动、输入或按钮点击。以下是几种常见的实现方式: 使用Lodash的throttle函数 安装L…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue nexttick 实现

vue nexttick 实现

Vue nextTick 实现原理 Vue 的 nextTick 是一个用于在下次 DOM 更新循环结束之后执行延迟回调的方法。它主要用于确保在 DOM 更新完成后执行某些操作。 核心实现机制 ne…

vue实现tabbar

vue实现tabbar

Vue 实现 TabBar 的方法 使用 Vue Router 实现基础 TabBar 安装 Vue Router 依赖: npm install vue-router 创建路由配置文件(route…

vue最佳实现

vue最佳实现

Vue 最佳实践 组件设计 组件应遵循单一职责原则,每个组件只负责一个功能模块。命名采用 PascalCase(如 UserProfile.vue),模板中使用 kebab-case(如 <us…

vue递归实现

vue递归实现

vue递归实现方法 在Vue中实现递归组件通常用于树形结构、嵌套菜单等场景。以下是具体实现方式: 使用组件name属性递归 定义一个组件时,通过name属性让组件可以在自身模板中调用自己:…