当前位置:首页 > VUE

vue实现缩略div

2026-03-10 10:06:20VUE

Vue 实现缩略 Div 的方法

使用 CSS 控制文本溢出

通过 CSS 的 text-overflow 属性可以实现文本缩略显示,适用于单行或多行文本截断。

<template>
  <div class="truncate">
    {{ longText }}
  </div>
</template>

<style>
.truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 200px; /* 固定宽度 */
}
</style>

多行文本缩略

通过 -webkit-line-clamp 实现多行文本缩略。

<template>
  <div class="multiline-truncate">
    {{ longText }}
  </div>
</template>

<style>
.multiline-truncate {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  width: 300px;
}
</style>

动态控制缩略与展开

结合 Vue 的 v-ifv-show 动态切换缩略和完整内容。

<template>
  <div>
    <p v-if="isTruncated" class="truncate">{{ longText }}</p>
    <p v-else>{{ longText }}</p>
    <button @click="isTruncated = !isTruncated">
      {{ isTruncated ? '展开' : '收起' }}
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      longText: '这是一段很长的文本...',
      isTruncated: true
    };
  }
};
</script>

使用第三方库

借助 vue-clampvue-text-clamp 等库实现更灵活的缩略功能。

安装 vue-clamp

npm install vue-clamp

使用示例:

<template>
  <v-clamp :max-lines="2" autoresize>
    {{ longText }}
  </v-clamp>
</template>

<script>
import VClamp from 'vue-clamp';
export default {
  components: { VClamp },
  data() {
    return { longText: '很长很长的文本...' };
  }
};
</script>

响应式宽度缩略

通过计算属性动态调整缩略宽度,适应不同屏幕尺寸。

vue实现缩略div

<template>
  <div class="responsive-truncate" :style="{ width: computedWidth }">
    {{ longText }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      longText: '响应式缩略文本...',
      screenWidth: window.innerWidth
    };
  },
  computed: {
    computedWidth() {
      return this.screenWidth < 768 ? '150px' : '250px';
    }
  },
  mounted() {
    window.addEventListener('resize', () => {
      this.screenWidth = window.innerWidth;
    });
  }
};
</script>

<style>
.responsive-truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>

标签: 缩略vue
分享给朋友:

相关文章

vue 路由实现

vue 路由实现

Vue 路由实现方法 安装 Vue Router 使用 npm 或 yarn 安装 Vue Router 依赖包: npm install vue-router # 或 yarn add vue-r…

vue实现视窗

vue实现视窗

Vue 实现视窗功能 在 Vue 中实现视窗功能通常涉及监听浏览器窗口大小变化、响应式布局或创建自定义弹窗组件。以下是几种常见实现方式: 监听浏览器窗口大小变化 使用 Vue 的 mounted 和…

vue实现grid

vue实现grid

Vue 实现 Grid 布局的方法 使用 CSS Grid 布局 Vue 可以结合 CSS Grid 布局实现灵活的网格系统。CSS Grid 是现代浏览器原生支持的布局方案,无需额外依赖库。 &l…

vue实现switch

vue实现switch

Vue 实现 Switch 开关组件 在 Vue 中实现 Switch 开关组件可以通过自定义组件或使用现有 UI 库完成。以下是几种常见实现方式: 自定义 Switch 组件 创建一个基础 Sw…

vue实现toast

vue实现toast

Vue 实现 Toast 的方法 使用第三方库(推荐) 对于快速实现 Toast 功能,推荐使用成熟的第三方库如 vue-toastification 或 vant 的 Toast 组件。 安装 v…

vue实现双向

vue实现双向

Vue 实现双向绑定的方法 Vue 的双向绑定主要通过 v-model 指令实现,它结合了数据绑定和事件监听,适用于表单元素(如 input、select、textarea 等)。以下是几种常见的实现…