vue 实现更多展开
Vue 实现更多展开功能
在 Vue 中实现“更多展开”功能可以通过多种方式完成,以下是几种常见的实现方法:
使用 v-show 或 v-if 控制显示
通过 Vue 的指令 v-show 或 v-if 动态控制内容的显示与隐藏。
<template>
<div>
<p>{{ truncatedText }}</p>
<button @click="toggleExpand">
{{ isExpanded ? '收起' : '展开更多' }}
</button>
<p v-show="isExpanded">{{ fullText }}</p>
</div>
</template>
<script>
export default {
data() {
return {
fullText: '这里是完整的长文本内容...',
isExpanded: false,
};
},
computed: {
truncatedText() {
return this.fullText.slice(0, 50) + '...';
},
},
methods: {
toggleExpand() {
this.isExpanded = !this.isExpanded;
},
},
};
</script>
使用 CSS 控制文本溢出
通过 CSS 的 text-overflow 和 max-height 属性实现展开与收起的效果。
<template>
<div>
<p :class="{ 'expanded': isExpanded }">{{ fullText }}</p>
<button @click="toggleExpand">
{{ isExpanded ? '收起' : '展开更多' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
fullText: '这里是完整的长文本内容...',
isExpanded: false,
};
},
methods: {
toggleExpand() {
this.isExpanded = !this.isExpanded;
},
},
};
</script>
<style>
p {
max-height: 60px;
overflow: hidden;
text-overflow: ellipsis;
transition: max-height 0.3s ease;
}
p.expanded {
max-height: 1000px;
}
</style>
使用第三方库
如果需要更复杂的功能(如动画、多行截断等),可以使用第三方库如 vue-show-more 或 vue-truncate-collapse。
<template>
<div>
<vue-show-more :text="fullText" :lines="2" />
</div>
</template>
<script>
import VueShowMore from 'vue-show-more';
export default {
components: {
VueShowMore,
},
data() {
return {
fullText: '这里是完整的长文本内容...',
};
},
};
</script>
动态计算文本高度
通过动态计算文本高度实现展开与收起的效果。
<template>
<div>
<p ref="content" :style="{ height: contentHeight }">{{ fullText }}</p>
<button @click="toggleExpand">
{{ isExpanded ? '收起' : '展开更多' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
fullText: '这里是完整的长文本内容...',
isExpanded: false,
contentHeight: '60px',
};
},
methods: {
toggleExpand() {
this.isExpanded = !this.isExpanded;
this.contentHeight = this.isExpanded ? 'auto' : '60px';
},
},
};
</script>
以上方法可以根据具体需求选择使用,灵活调整实现方式。







