Vue 中文本内容超出规定行数后展开收起的处理的实现方法

2020-06-16 06:10:40易采站长站整理

文字比较难解释,直接看图应该就懂是要做什么了。

需求

工作中遇到的,需求就是超过四行得有个展开按钮,点击展开显示所有内容,不超过四行的话就不需要这个按钮并显示所有内容。

思路首先得判断文本自否超过四行,因为这些一般都是是前端异步请求然后后端发送过来,在组长的指导下,使用了 Vue 中的 nextTick 来监听 DOM 中是数据变化。接下来主要是 css 上的思路,其实上图可以分为两部分,如下图,标号1的部分展示前面三行,标号为2的部分会根据1的行数判断缩进的大小,然后展示第四行。最后通过背景色的控制让两者看上去是一段文字。

代码

核心代码是中间那部分,其他的不用关注


<template>
<div>
<div style="text-align: center">{{title}}</div>
<div class="top-prove">为了证明楼下的那货不会对我造成影响</div>
<div :class="showTotal ? 'total-introduce' : 'detailed-introduce'">
<div class="intro-content" :title="introduce" ref="desc">
<span class="merchant-desc" v-if="introduce">
{{introduce}}
</span>
<div class="unfold" @click="showTotalIntro" v-if="showExchangeButton">
<p>{{exchangeButton ? '展开' : '收起'}}</p>
</div>
</div>
</div>
<div class="bottom-prove">为了证明楼上的那货不会对我造成影响</div>
<div class="change-buttom">
<div class="long" @click="tryLong">点这试试一段比较长的文字</div>
<div class="short" @click="tryShort">点这试试一段比较短的文字</div>
</div>
</div>
</template>

<script>
export default {
name: 'Spread',
data () {
return {
title: '演示展开收起',
introduce: '',
// 是否展示所有文本内容
showTotal: true,
// 显示展开还是收起
exchangeButton: true,
// 是否显示展开收起按钮
showExchangeButton: false,
rem: ''
};
},
mounted () {
this.init();
},
methods: {
showTotalIntro () {
console.log(this.showTotal);
this.showTotal = !this.showTotal;
this.exchangeButton = !this.exchangeButton;
},
getRem () {
console.log('getRem');
const defaultRem = 16;
let winWidth = window.innerWidth;
console.log('winWidth:' + winWidth);
let rem = winWidth / 375 * defaultRem;