<template>
<div id="app">
<el-button size="small" @click="search"> 全部展开 </el-button>
<el-button size="small" @click="close"> 全部收起 </el-button>
<el-tree
:props="defaultProps"
:data="treeData"
lazy
:load="loadNode"
ref="tree"
:defaultExpandedKeys="defaultExpandedKeys"
node-key="id"
>
</el-tree>
</div>
</template>
<script>
export default {
name: "app",
data() {
return {
defaultProps: {
children: "children",
label: "label",
isLeaf: false,// 'leaf'
},
defaultExpandedKeys: [],
fakeId: 2,
ids: [],
treeData: [],
};
},
methods: {
close() {
const tree = this.$refs.tree;
if (tree) {
this.ids = [];
this.traverseNodes(tree.store.root);
this.expandNodes(this.$refs.tree.store.root);
console.log(this.ids, '拿到所有id');
}
},
traverseNodes(node) {
if (!node) {
return;
}
this.ids.push(node.id);
if (node.childNodes && node.childNodes.length > 0) {
for (let i = 0; i < node.childNodes.length; i++) {
this.traverseNodes(node.childNodes[i]);
}
}
},
// 遍历树形数据,设置每一项的expanded属性,实现展开收起
expandNodes(node) {
node.expanded = this.expandAll;
for (let i = 0; i < node.childNodes.length; i++) {
node.childNodes[i].expanded = this.expandAll;
if (node.childNodes[i].childNodes.length > 0) {
this.expandNodes(node.childNodes[i]);
}
}
},
search() {
const tree = this.$refs.tree;
if (tree) {
this.expandAllNodes(tree.store.root.childNodes);
}
// 展开是拿到所有id的方法目前没试过
// this.defaultExpandedKeys = [8, 9, 1, 4, 3, 6, 5];
},
expandAllNodes(nodes) {
for (const node of nodes) {
if (node.childNodes && !node.expanded) {
node.expand();
}
if (node.childNodes && node.childNodes.length > 0) {
this.expandAllNodes(node.childNodes);
}
}
},
getTree() {
return this.$refs.tree;
},
loadNode(node, resolve) {
setTimeout(() => {
if (node.level === 0) {
resolve([
{
id: 1,
label: "1",
children: [],
},
{
id: 2,
label: "2",
children: [],
},
]);
}
const data = [];
this.fakeId++;
data.push({
id: this.fakeId,
label: this.fakeId,
children: [],
});
// data.forEach((value) => {
// if (value.children.length === 0) {
// value.leaf = true; // true 代表是末节点 接口要返回表示是不是末节点
// } else {
// value.leaf = false;
// }
// });
resolve(data);
}, 500);
},
},
};
</script>
<style lang="scss" scoped></style>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
}
</style>
版权声明:本文为qq_44716001原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。