首先来看看最终实现的效果:
这是一个搜索功能的分类字段,此时暂时显示的是两层数据,会根据后端所传递的数据多层次渲染。在element ui中单一的的组件库并不能满足这个功能的需求,因此使用select和tree两个组件相结合将这个功能点解决。
话不多说,上代码:
1.组件结构:
mineStatus:select组件绑定的字段,在tree组件数据处理的方法中赋值。
multiple:是否多选。
mineStatusValue: option组件绑定的数据。
data:tree组件的数据绑定,通过后端将数据拿到,再使用递归方法将数据处理为tree组件所需要的数据结构。
show-checkbox:节点是否可被选择。
check-strictly:在显示复选框的情况下,是否严格的遵循父子不互相关联的做法。
node-key:每个树节点用来作为唯一标识的属性,整棵树应该是唯一的。
highlight-current:是否高亮当前选中节点。
props:tree组件的配置选项,一般为一个json对象,里面包含label、children、disabled、isLeaf四个字段。
check-change:tree组件节点选中状态发生变化时的回调。
```
<el-select v-model="statusData" placeholder="课程分类筛选" multiple>
<el-option :value="statusValueData" style="height: auto">
<el-tree :data="data" show-checkbox node-key="id" check-strictly ref="tree" highlight-current :props="defaultProps" @check-change="handleCheckChange"></el-tree>
</el-option>
</el-select>
```
2.数据处理:根据数据对选中的值进行赋值,调用搜索的接口方法进行搜索。
setCheckedNodes:设置目前勾选的节点,使用此方法必须设置 node-key 属性。
getCheckedNodes:若节点可被选择(即 show-checkbox 为 true),则返回目前被选中的节点所组成的数组。
```
// tree数据处理方法
handleCheckChange(data,checked, node) {if(checked){
this.$refs.tree.setCheckedNodes([data]);
}
let response=this.$refs.tree.getCheckedNodes(false,true);
let labelData = [];
let arrData = [];
response.forEach(item => {
labelData.push(item.label);
arrData.push(item);
});
this.statusValueData = arrData;
this.statusData = labelData;if(res.length && res[0].id ==data.id){this.categoryId =data.id;
data.id?this.getpersonalCourseData():"";
}else if(!res.length){
this.categoryId ="";this.getpersonalCourseData();//调用搜索功能的方法
}
},
```
3.递归的封装:处理从后端拿回来的分类数据,然后将数据结构使用递归方法处理,转换成tree组件的所需要的数据结构。
```
recursionFun(data){
constarrData = [];
let objData = {};
data.forEach(item=>{
constrecursionData = { ...item };
if(recursionData.children){
recursionData.children =this.recursionFun(recursionData.children);
objData = {
id:recursionData.id,
label:recursionData.categoryName,
children:recursionData.children
}
}
arrData.push(objData);
})
return arrData;
}
```