vue实现缩略div
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-if 或 v-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-clamp 或 vue-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>
响应式宽度缩略
通过计算属性动态调整缩略宽度,适应不同屏幕尺寸。
<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>






