el-tree默认展开n项,最后一项时调用接口获取
1、一开始想的使使用el-tree懒加载的方法,但后续执行效果不理想,懒加载方法只能搜索第一层的内容,无法搜索到所有的默认展开项。
后面直接不用懒加载的方法,直接通过节点判断调用接口,可以实现搜索功能。
<el-input
placeholder="请输入查找内容"
prefix-icon="el-icon-search"
v-model="filterText"
>
</el-input>
<el-tree
:props="props"
:data="treedep"
node-key="id" //对每个节点命名id
@node-click="nodeClick" //点击节点时触发
:default-expanded-keys="defaultExpandedKeys"
:filter-node-method="filterNode"
ref="leftTree"
>
</el-tree>
data中的内容:
treedep:[],
filterText: "",
props: {
label: "deptName",
children: "children", //子节点所在的数组对象名
isLeaf: "leaf",
},
方法:
nodeClick(data,node){
if(data.xxx){
// 如果存在已经调用完接口的数据则...
}else{
this.defaultExpandedKeys = []
if(!node.data.children && node.level >= 1){ //当不存在子节点时,并且层级大于等于1时才会触发接口
接口名().then((res) => {
let list = res.data.data.map((e) => {
...
return e;
});
this.$set(node.data, 'children', []);
node.data.children = list
this.defaultExpandedKeys2.push(data.id)
// 这一步是将获取到的数据插入到子节点中
});
}
}
}
监听filterText实时对搜索内容进行监控:
watch: {
filterText(val) {
this.$refs.leftTree.filter(val); //自带的过滤方法
},
},