信息发布→ 登录 注册 退出

vue element-ul实现展开和收起功能的实例代码

发布时间:2026-01-10

点击量:
目录
  • 实现效果如下:
  •  需求:
  • 需求分析:
  • 解决思路:
  • 代码解析:
  • 新方法:

实现效果如下:

 需求:

由于后台搜索选项有很多,影响页面美观,所以一进来要隐藏一部分搜索项,只保留1行,

点击【展开搜索】按钮的时候才显示全部,点击【收起搜索】按钮又收起部分,保留1行。

需求分析:

由于不太好控制行数,因为不同屏幕尺寸展示的1行的内容并不相同(不考虑移动端),所以考虑用显示高度来控制。

解决思路:

所以这里通过控制搜索区域的高度来实现展开和收起搜索功能。

页面一进来是收起搜索状态,控制搜索区域的高度为120px,超出部分隐藏。

点击展开搜索的时候,调整搜索区域的高度为”auto"

 定义变量:showAll控制状态

代码解析:

 <el-button type="text" style="margin-left:10px" id="closeSearchBtn" @click="closeSearch">
     {{word}}
     <i :class="showAll ? 'el-icon-arrow-up ': 'el-icon-arrow-down'"></i>
    </el-button>

当showAll为false的时候,即搜索区域处于收起状态,此时将按钮文字变为“展开搜索”,图标变为向下(el-icon-arrow-down)

当showAll为ture的时候,即搜索区域全部展开了,将按钮文字变成“收起搜索”,图标变成向上(el-icon-arrow-up)

data(){
  return{
   showAll:true;//是否展开全部
 
  }
}
computed: {
  word: function() {
   if (this.showAll == false) {
    //对文字进行处理
    return "展开搜索";
   } else {
    return "收起搜索";
   }
  }
 },

mounted()里调用closeSearch函数,页面一进来将this.showAll设为false,即处于收起状态。所以data里最初给showAll定义的时候设为true.

给搜索区域的ID设为“searchBox”  ,

当showAll为false的时候,设置搜索区域高度为120px,否则高度自动。

mounted() {
  /**
   * 收起搜索
   */
  this.$nextTick(function() {
   this.closeSearch();
  });
 },
 methods:{
  closeSearch() {
   this.showAll = !this.showAll;
   var searchBoxHeght = document.getElementById("searchBox");
   if (this.showAll == false) {
    searchBoxHeght.style.height = 60 + "px";
   } else {
    searchBoxHeght.style.height = "auto";
   }
  }
 }

CSS中关键的设置不要忘记。

#searchBox {
 overflow: hidden;
}

新方法:

html:

    :style="{
                height: showMoreSearch
                    ? `${searchboxHeight - searchboxOtherHeight}px`
                    : `${searchboxDefaultHeight}px`
            }">
        <el-button
                class="more-arrow"
                type="text"
                title="更多查询条件"
                @click="toggleSearch(1)">
                {{ searchTitle }}
                <i class="el-icon-arrow-down more-arrow"></i>
            </el-button>

data:

   showMore: false, // 是否下拉显示更多
            searchTitle: "显示全部"

methods:

   // 显示更多(rows为下拉的行数,根据下拉行数计算高度)
        toggleSearch (rows = 1) {
            this.showMoreSearch = !this.showMoreSearch;
            this.searchTitle = this.showMoreSearch ? "收起" : "显示全部";
            this.searchboxHeight = this.showMoreSearch ? rows * 64 + 200 : 200;
        },
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!