vue实现查看更多
Vue 实现“查看更多”功能
在 Vue 中实现“查看更多”功能通常涉及动态控制内容的显示与隐藏,以下是几种常见方法:
使用 v-if 或 v-show 控制内容显示
通过布尔值切换内容的展开与折叠状态:
<template>
<div>
<p v-if="!isExpanded">{{ truncatedText }}</p>
<p v-else>{{ fullText }}</p>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '查看更多' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
fullText: '这里是完整的文本内容...',
truncatedText: '这里是截断的文本...',
isExpanded: false
}
}
}
</script>
使用 CSS 控制文本溢出
通过 CSS 的 text-overflow 和 max-height 动态切换样式:
<template>
<div>
<p :class="{ 'truncate': !isExpanded }">{{ fullText }}</p>
<button @click="isExpanded = !isExpanded">
{{ isExpanded ? '收起' : '查看更多' }}
</button>
</div>
</template>
<style>
.truncate {
display: -webkit-box;
-webkit-line-clamp: 3; /* 限制行数 */
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>
结合计算属性动态截取文本
通过计算属性实现动态文本截取:
<template>
<div>
<p>{{ displayText }}</p>
<button @click="toggleExpand">
{{ isExpanded ? '收起' : '查看更多' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
fullText: '长文本内容...',
isExpanded: false,
maxLength: 100
}
},
computed: {
displayText() {
return this.isExpanded
? this.fullText
: this.fullText.slice(0, this.maxLength) + '...';
}
},
methods: {
toggleExpand() {
this.isExpanded = !this.isExpanded;
}
}
}
</script>
使用第三方库(如 vue-show-more)
对于更复杂的需求,可以使用专门库简化实现:
npm install vue-show-more
<template>
<vue-show-more
:text="fullText"
:max-chars="100"
:toggle="true"
/>
</template>
注意事项
- 性能考虑:长文本频繁切换时,优先使用
v-show而非v-if。 - 无障碍访问:为按钮添加
aria-expanded属性提升可访问性。 - 国际化:按钮文本建议通过
i18n管理多语言场景。







