当我们在项目中使用element plus的树型控件时
可能会遇到数据太多导致树结构过长的情况,若用户想要查看所有的数据结点,则需要一个一个去展开,着实影响用户体验。
这种情况我们可以用树形控件的 default-expand-all 属性,令其默认全部展开
default-expand-all
<el-tree :data="treeData" :props="treeProps" default-expand-all show-checkbox ref="folderTreeRef" />
html
但是默认展开后的树占用了非常大的空间,也会影响用户体验,于是我们可以增加一个按钮来控制树型结构的展开和收缩。
这么简单的功能element官方应该会有API提供吧,但是当我们去官方文档中找时,发现根本没有这个API
但是当我们输出Tree组件时,可以发现其实是有控制节点展开或收起的属性的
const folderTreeRef = ref(null);
console.log("@", folderTreeRef.value)
javascript
运行
于是我们可以手动给它展开收起
先定义个按钮
<div class="addContactBtn" @click="isShowMore()">
<div class="icon">
<el-icon v-if="zhanstatus % 2 == 0">
<Plus />
</el-icon>
<el-icon v-else>
<Minus />
</el-icon>
</div>
<div class="addNewCon">{{ zhanstatus % 2 == 0 ? 'Show More' : 'Show Less' }}</div>
</div>
html
样式
.addContactBtn {
display: flex;
align-items: center;
cursor: pointer;
margin-top: 8px;
margin-left: 50px;
.icon {
width: 20px;
height: 20px;
border-radius: 20px;
border: 1px solid #0085D0;
background: #E9F2FB;
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
color: #0085D0;
}
.addNewCon {
margin-left: 8px;
color: #0085D0;
text-align: center;
font-size: 12px;
font-style: normal;
font-weight: 510;
line-height: 20px;
}
}
css
逻辑代码
const zhanstatus = ref(1);
function isShowMore() {
zhanstatus.value++;
if (zhanstatus.value % 2 == 0) {
let nodes = folderTreeRef.value.store._getAllNodes();
nodes.forEach(item => {
item.expanded = false;
});
} else {
let nodes = folderTreeRef.value.store._getAllNodes();
nodes.forEach(item => {
item.expanded = true;
});
}
}
javascript
运行
最终实现效果