介绍el-tree的通用图层模板和一些常用方法
介绍方法:
- 展开全部节点和关闭全部节点
- 全选图层树,全不选图层的方法
- 点击复选框触发的方法
- 控制节点的收缩和隐藏
废话不说:直接看代码,注释比较多,请耐心看完
<template>
<div class="tree">
<!-- default-expand-all 为节点全部展开,如果不展开的话无法触发子集的方法 -->
<!-- node-key为节点的唯一依据 -->
<el-tree :data="data" ref="tcTree" :highlight-current='true' :default-expand-all="true" :props="{
children: 'children',
label: 'label'
}" node-key="label" show-checkbox @check-change="clickNode"></el-tree>
</div>
</template>
<script>
export default {
data() {
return {
data: [{
label: 'Level one 1',
children: [
{
label: 'Level two 1-1',
children: [
{
label: 'Level three 1-1-1',
},
],
},
],
},
{
label: 'Level one 2',
children: [
{
label: 'Level two 2-1',
children: [
{
label: 'Level three 2-1-1',
},
],
},
{
label: 'Level two 2-2',
children: [
{
label: 'Level three 2-2-1',
},
],
},
],
},
{
label: 'Level one 3',
children: [
{
label: 'Level two 3-1',
children: [
{
label: 'Level three 3-1-1',
},
],
},
{
label: 'Level two 3-2',
children: [
{
label: 'Level three 3-2-1',
},
],
},
],
},
]
}
},
mounted() {
//会触发全部的节点的clickNode方法
this.$refs.tcTree.setCheckedKeys(this.getAllNodes(this.data)); // 全选节点
this.$refs.tcTree.setCheckedKeys([]); // 全部节点不选的方法
//this.$refs.tcTree.store.root这个方法可以获得所有节点的展开和选中信息和完整信息
console.log(this.$refs.tcTree.store.root);
this.changeTreeNodeStatus(this.$refs.tcTree.store.root) //展开或者关闭所有节点全部节点的方法
},
methods: {
//点击复选框触发的函数
clickNode(node, checked, childChecked) {
console.log(node, '点击的节点的信息');
console.log(checked, '当前节点的状态');
console.log(childChecked, '子节点是否有被选中的'); //一般不用这个属性
//可以根据node内的数据执行不同的操作
},
//递归所有节点的信息。。。
getAllNodes(node = [], arr = []) {
for (let item of node) {
arr.push(item.label)
let parentArr = []
if (item.children) parentArr.push(...item.children)
if (parentArr && parentArr.length) this.getAllNodes(parentArr, arr)
}
return arr
},
//设置全部节点的关闭或者开启状态
changeTreeNodeStatus(node) {
console.log(node);
//全部节点的状态设置;为true就是全部展开,为false全部关闭
let allZt = true
node.expanded = allZt
for (let i = 0; i < node.childNodes.length; i++) {
// 改变节点的自身expanded状态
node.childNodes[i].expanded = allZt
// 遍历子节点
if (node.childNodes[i].childNodes.length > 0) {
this.changeTreeNodeStatus(node.childNodes[i])
}
}
},
},
}
</script>
<style lang="scss" scoped>
</style>
```