需要实现的效果:
-
带展开/收起按钮,列表默认展示
两条
数据
-
展开时只展示
四条
数据,其余通过滚动条
查看
页面效果实现
- 外层使用div控制列表的展示数目(高度height);
- class
itemBoard
定义样式,iditemBoard
用于获取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
用来实现动态删除数组元素