页面主题代码
<template>
<div class="app-container" style="padding: 10px;">
<el-container>
<el-main>
<el-col :span="6">
<el-row style="margin-top: 10px; margin-left: 10px; width: 95%;">
<el-input size="mini" placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
</el-row>
<el-row style="margin-top: 10px;">
<el-tree
class="filter-tree"
:data="treeList"
node-key="id"
accordion
:default-expanded-keys="[1,2]"
:filter-node-method="filterNode"
:expand-on-click-node="false"
highlight-current
:render-content="renderContent"
ref="tree" @node-click="nodeClick">
</el-tree>
</el-row>
</el-col>
</el-main>
</el-container>
</div>
</template>
需要注意的是,如果一个页面含有多个树结构,那么上述 v-model=“filterText” 和 ref="tree"需要区分,最简单的可以filterTextOne、filterTextTwo… ;treeOne、treeTwo…
Js部分代码
<script>
export default {
watch: {
filterText(val) {
this.$refs.tree.filter(val);
}
},
data () {
return {
filterText: '',
treeList: [{
id: '1',
label: '班级',
children: [{
id: '2',
label: '班级1',
children: [{id: '3', label: '小红'}, {id: '4', label: '小明'}]
},{
id: '5',
label: '班级2',
children: [{id: '6', label: '小亮'}, {id: '7', label: '小黑'}]
}]
}]
}
},
methods: {
// 树结构关键字查询
filterNode(value, data, node) {
if (!value) return true;
let parentNode = node.parent, labels = [node.label], level = 1
while (level < node.level) {
labels = [...labels, parentNode.label]
parentNode = parentNode.parent
level++
}
return labels.some(label => label.indexOf(value) !== -1)
},
}
}
</script>
Js部分需要注意的是,watch: {}中,如有多个树结构,则需要写多个,特别注意其中 filterText 和 tree(ref=tree)不同:
watch: {
filterTextOne(val) {
this.$refs.treeOne.filter(val);
},
filterTextTwo(val) {
this.$refs.treeTwo.filter(val);
}
}
有多个树结构时,data () { return{} }中,也需要声明多个filterText:
data () {
return {
filterTextOne: '',
filterTextTwo: ''
}
}
效果展示: