vuejs数据超出单行显示更多,点击展开剩余数据实例

2020-06-16 05:57:29易采站长站整理

说下我在工作中遇到的这个需求

1:页面上的菜单选项,选项内容是后台接口返回的数据,现在的需求是当选项的内容超出一行,在这行的右面显示更多,点击更多,显示剩下的选项的内容

看下效果图

这是展开的效果图

 

下面先看下我的html部分代码


<div :class="bussinessType?'show':'hidde'">
<dl>
<dt>业务类型:</dt>
<dd ref="bussinessTypeRef">
<a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" name=""
@click="getchildMenu($event)" class="active">全部</a>
<a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" :name="item.code" v-for="item in projectType"
@click="getchildMenu($event)">{{item.name}}</a>
</dd>
<i class="unfold" @click="bussinessType = !bussinessType"
v-show="bussinessHeight>40">
{{ bussinessType ? '收起' : '更多'}}
<Icon :type="bussinessType?'chevron-down':'chevron-up'" ></Icon>
</i>
</dl>
</div>

说下原理show就是展开的时候使用的样式名称,hide是显示一行是使用的样式(主要就是控制容器高度)


.show{
        height: auto;
        border-bottom: 1px solid #ebebeb;
    }
    .hidde{
        height: 40px;
        overflow: hidden;
        border-bottom: 1px solid #ebebeb;
    }

这是我展示的菜单的部分,主要的思路是看这部分的高度是不是超出一行的高度,如果是超出一行的高度,则让dl外的div默认使用hide的样式

那么问题来了,怎么知道展示菜单的dd部分的高度超出一行了呢?

这就需要使用vuejs的watch来实现了

首先,watch监听ref是bussinessTypeRef的组件的高度(内容多的话自然dd容易会被撑高),这时候与一行的高度(我这里设置的是40)作比较,如果超出,就让更多的文字按钮显示出来。下面是监听dd内容高度的watch方法