Html+Element UI+JS实现列表展开收起效果

需要实现的效果

  • 带展开/收起按钮,列表默认展示两条数据
    在这里插入图片描述

  • 展开时只展示四条数据,其余通过滚动条查看
    在这里插入图片描述

页面效果实现

  • 外层使用div控制列表的展示数目(高度height);
  • class itemBoard定义样式,id itemBoard 用于获取div节点对象;
  • v-show控制按钮展示与否(注意:v-show是根据表达式决定是否展示已在 - 页面渲染的内容,v-if是根据表达式决定是否渲染页面内容);
  • closeItemShow展开/收起列表按钮事件;
  • showMoreText动态展示按钮文本(展开/收起);
  • 使用vue组件v-for迭代数组实现列表效果;
  • 在data里面声明showAll默认true,表示是否展开列表
<!-- 事项列表 -->
<div class="itemBoard" id="itemBoard">
    <!-- 展开/收起按钮 -->
    <el-button
        type="text"
        style="float: right; margin-right: -15px;"
        @click="closeItemShow"
        v-show="form.chooseItems.length > 0">
        {{showMoreText}}
        <i :class="showAll ? 'el-icon-arrow-up ': 'el-icon-arrow-down'"></i>
    </el-button>
    <div v-for="(item, index) in form.chooseItems" :key="index">
        {{ item.itemName }}
        <el-button size="medium" type="text" icon="el-icon-circle-close" @click="handleDelItem(item)"></el-button>
    </div>
</div>

动态切换展开/收起按钮文本

在computed监控showMoreText变量,该变量不在data里面声明,直接在computed里面定义,然后在页面上进行双向数据绑定

computed: {
    showMoreText: function () {
        if (this.showAll) {
            return '收起';
        }

        return '展开';
    }
},

按钮事件closeItemShow

先修改showAll的值,获取div节点对象以操作样式

// 展开/收起列表
closeItemShow() {
    this.showAll = !this.showAll;
    let itemBoardStyle = document.getElementById("itemBoard");
    if (this.showAll) {
        // 列表展开,设定只展示四条数据的高度
        itemBoardStyle.style.height = 160 + 'px';
        // 设置overflow属性规定当内容溢出元素框时显示滚动条
        itemBoardStyle.style.overflow = 'auto';
    } else {
        // 列表收起,设定只展示两条数据的高度
        itemBoardStyle.style.height = 80 + 'px';
        // 设置overflow属性规定当内容溢出元素框时隐藏内容
        itemBoardStyle.style.overflow = 'hidden';
    }
},

页面初始化时候默认列表收起

showAll在data默认true,初始化时调用closeItemShow方法(非唯一方式)

mounted() {
    // 初始化事项列表
    this.$nextTick(function () {
        this.closeItemShow();
    });
},

div样式

overflow默认hidden,表示当内容溢出元素框时隐藏内容

.itemBoard {
    background-color: rgba(241, 244, 250, 1);
    padding: 5px 20px;
    overflow: hidden;
}

Tips

  • overflow值
    在这里插入图片描述
  • 页面代码底下的el-button用来实现动态删除数组元素
posted @ 2022-03-10 23:02  →_→BéLieve  阅读(62)  评论(0)    收藏  举报  来源