el-tree的数据是用内部实现的一个node-store存储的,没有直接对外提供过滤后的数据,但是可以通过refs拿到带visible属性的所有节点数据:this.$refs.tree.store.root.childNodes
通过两个递归方法,可以从这个childNodes中提取出想要的数据。如下图:
完整代码demo地址:demo
<script src="//unpkg.com/vue@2/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.15.8/lib/index.js"></script>
<div id="app">
<el-input placeholder="输入关键字进行过滤" v-model="filterText"> </el-input>
<el-tree
class="filter-tree"
:data="data"
:props="defaultProps"
default-expand-all
:filter-node-method="filterNode"
ref="tree"
>
</el-tree>
<el-row>
<el-button type="primary" @click="setCurrentData">获取当前node数据</el-button>
</el-row>
<el-row>
<div>{{current}}</div>
</el-row>
</div>
var Main = {
watch: {
filterText(val) {
this.$refs.tree.filter(val);
}
},
methods: {
filterNode(value, data) {
if (!value) return true;
return data.label.indexOf(value) !== -1;
},
filterItem(value, data) {
if (!value) return true;
return data.text.indexOf(value) !== -1;
},
// 获取过滤后的数据的操作代码
setCurrentData() {
const traverseNode = function(node) {
if (Object.prototype.toString.call(node) === '[object Array]') {
return node.map(t => traverseNode(t))
}
const data = {id: node.id, label: node.label, visible: node.visible, children: []}
const childNodes = node.childNodes;
childNodes.forEach((child) => {
const item = traverseNode(child)
if (item.visible) {
data.visible = true
}
data.children.push(item)
});
return data
};
const traverseVisible = function(arr) {
return arr.filter(t => {
let visible = t.visible
if (!visible) {
return false
}
if (t.children) {
t.children = traverseVisible(t.children)
}
delete t.visible
return visible
})
}
const data = traverseNode(this.$refs.tree.store.root.childNodes)
this.current = traverseVisible(data)
}
},
data() {
return {
filterText: '',
data: [{
id: 1,
label: '一级 1',
children: [{
id: 4,
label: '二级 1-1',
children: [{
id: 9,
label: '三级 1-1-1'
}, {
id: 10,
label: '三级 1-1-2'
}]
}]
}, {
id: 2,
label: '一级 2',
children: [{
id: 5,
label: '二级 2-1'
}, {
id: 6,
label: '二级 2-2'
}]
}, {
id: 3,
label: '一级 3',
children: [{
id: 7,
label: '二级 3-1'
}, {
id: 8,
label: '二级 3-2'
}]
}],
defaultProps: {
children: 'children',
label: 'label'
},
current: {},
};
}
};
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')