vue 文本超过三行添加展开/收起

思路:1、判断当前内容是否超过三行。此处可以给每行设置一个行高line-height,渲染完后超过三倍的行高即认为是内容超过了三行。2、展示/收起状态的切换

 

1、vue设置这里是一个循环,此处不在粘贴最外层的循环。

<el-form-item label="内容">

                            <span :ref="'FTcontent'+item.index"

                                  :class="{formitemcontent: (item.ifShow && item.ifShowZK)}">{{ item.Content }}</span>

                            <div class="unfold"

                                 :class="{unfoldselect:!item.ifShowZK}"

                                 v-if="item.ifShow">

                              <p @click="item.ifShowZK=!itemifShowZK,$forceUpdate()">{{item.ifShowZK ? '展开' : '收起'}}</p>

                            </div>

                          </el-form-item>

1.1 、ifShow   ifShowZK  两个属性是在拿到datalist以后循环添加的

    datalist.forEach((item, index) => {

              item.ifShow = false;//控制是否是三行样式

              item.ifShowZK = true;//控制展开/收起显示

            });

 

2、在组件初始化渲染完以后,判断行高是否超出了三行。(请参考vue的生命周期,此处我放在了updated)

updated() {

    let me = this;

    me.$nextTick(() => {

      me.tabTimeList.forEach((item, index1) => {

          datalist.forEach((item, index2) => {

            var vheight = me.$refs[`FTcontent${index2}`][0].offsetHeight;//获取当前span的高度

            //样式中的行高是40,超过3行高120,即显示展开

            if (vheight > 120) {

              item.ifShow = true;

          });

        }

      });

    })

  }

 

3、样式

.formitemcontent {

              height: 100%;

              overflow: hidden;

              text-overflow: ellipsis;

              display: -webkit-box;

              -webkit-line-clamp: 3; //这儿的数字代表的就是你所需要实现效果的第N行

              -webkit-box-orient: vertical;

            }

            .unfold {

              display: block;

              z-index: 11;

              float: left;

              width: 40px;

              height: 40px;

              p {

                margin: 0;

                line-height: 40px;

                color: #00a0e9;

                cursor: pointer;

              }

            }

            .unfoldselect {

              display: -webkit-inline-box;

              float: none;

            }

4、结果显示(不满三行的正常显示)

5、注意,这里需要$forceUpdate()强制刷新下组件。