起因:
进入公司后需要对一个老项目进行维护,对树组件新增一个过滤函数,前端使用的是莫名其妙的<ht-base-tree/>不知道什么玩意,于是自己写了一个过滤树函数。
适用范围:
树的每一个元素都是一个node,而结构必须包含一个children数组,其中children数组的每个元素都是node,网上其他地方搜到的教程中,树中的元素是数组,而这个例子中,树中元素是json对象。
解决方案:
data(){
return{
value: '',//类目树上面的搜索框绑定的变量
originalTreeData: [], // 存原始树数据
localTreeData: [], // 本地的树数据副本
}
},
// 当类目树搜索框搜索时执行的函数
// val是输入框中的过滤字段
// 当输入框的内容改变时执行 searchFn 函数
searchFn(val) {
if (val === null || val === '') this.reset()
this.localTreeData = this.filterTree(val, this.originalTreeData);
},
// 真实的过滤函数
// .map中对 children 进行过滤,递归
// 同时 .filter中对文案进行过滤,这里是对title和val进行匹配过滤
filterTree(val, tree) {
return tree.map(item => ({
...item,
children: item.children
? this.filterTree(val, item.children)
: null
})).filter(item => {
// 过滤掉没有子节点的节点
return item.title.includes(val)
|| (item.children != null && item.children.length > 0)
});
},
// 重置函数
reset() {
this.value = '';
this.localTreeData = this.originalTreeData
},
// props传值函数
// 其中treeData为其他组件传给props的值
watch: {
treeData(newValue) {
this.originalTreeData = JSON.parse(JSON.stringify(newValue));
this.localTreeData = JSON.parse(JSON.stringify(newValue));
}
},
坑点:
- 这里是封装了一个组件,包括输入框,重置按钮以及树,但是由于props渲染问题,必须使用watch才能拿到props传来的treedata值