el-tree懒加载状态下实现搜索筛选(纯前端)
1.效果图
(1)初始状态
(2)筛选后
2.代码
<template>
<div>
<el-input
placeholder="输入关键字进行过滤"
v-model="filterText"
@input="searchValue"
>
</el-input>
<el-tree
class="filter-tree"
node-key="id"
:lazy="!openAll"
:load="loadNode"
:data="dataTree"
:props="defaultProps"
:default-expand-all="openAll"
ref="tree"
>
</el-tree>
</div>
</template>
<script>
export default {
data() {
return {
openAll: false,
filterText: '',
dataTree: [
{
id: 1,
label: 'xx公司',
children: [
{
id: 3,
label: '公关',
children: [
{
id: 6,
label: '张三'
},
{
id: 7,
label: '李四'
}
]
},
{
id: 8,
label: '公关领导'
}
]
},
{
id: 2,
label: 'yy娱乐',
children: [
{
id: 4,
label: '王五'
},
{
id: 5,
label: '赵六'
}
]
}
],
defaultProps: {
children: 'children',
label: 'label',
isLeaf: 'isLeaf',
id: 'id'
},
dataTree1: []
}
},
created() {
this.dataTree1 = JSON.parse(JSON.stringify(this.dataTree))
},
methods: {
searchValue() {
this.$nextTick(() => {
if (
this.filterText &&
this.filterText !== '' &&
this.filterText !== null
) {
this.openAll = true
//关闭懒加载
this.$refs.tree.$data.store.lazy = false
//全部展开
this.$refs.tree.$data.store.defaultExpandAll = true
//深拷贝
let options = JSON.parse(JSON.stringify(this.dataTree))
//清空
this.$set(this, 'dataTree', [])
//筛选要显示的节点
this.searchTrees(options, this.filterText)
//重新赋值
this.$set(this, 'dataTree', options)
} else {
this.openAll = false
this.$refs.tree.$data.store.lazy = true
this.$refs.tree.$data.store.defaultExpandAll = false
this.$set(this, 'dataTree', this.dataTree1)
}
})
},
//循环树筛选要显示的节点
searchTrees(arr, val) {
let flag = false
if (arr && arr.length > 0) {
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i].children && arr[i].children.length > 0) {
let tempflag = this.searchTrees(arr[i].children, val)
if (tempflag == false) {
arr.splice(i, 1)
} else {
flag = true
}
} else {
if (arr[i].label.indexOf(val) === -1) {
arr.splice(i, 1)
} else {
flag = true
}
}
}
return flag
}
},
//懒加载(根据自己的数据来写)
loadNode(node, resolve) {
this.$nextTick(() => {
if (this.openAll === false) {
if (node.level === 0) {
let topData = []
this.dataTree.forEach(item => {
topData.push({ label: item.label, id: item.id, isLeaf: false })
})
return resolve(topData)
}
//一级下拉
if (node.level === 1) {
let firstData = []
this.dataTree.forEach(item => {
if (item.id === node.data.id) {
item.children.forEach(e => {
firstData.push({
label: e.label,
id: e.id,
isLeaf: e.children ? false : true
})
})
}
})
return resolve(firstData)
}
// 二级下拉
if (node.level === 2) {
let secondData = []
this.dataTree.forEach(item => {
item.children.forEach(e => {
if (e.id === node.data.id) {
e.children.forEach(i => {
secondData.push({
label: i.label,
id: i.id,
isLeaf: true
})
})
}
})
})
return resolve(secondData)
}
}
})
}
}
}
</script>
原文地址:https://blog.csdn.net/m0_74824076/article/details/144432726
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!