首先來看看最終實現(xiàn)的效果:

這是一個搜索功能的分類字段,此時暫時顯示的是兩層數(shù)據(jù),會根據(jù)后端所傳遞的數(shù)據(jù)多層次渲染。在element?ui中單一的的組件庫并不能滿足這個功能的需求,因此使用select和tree兩個組件相結合將這個功能點解決。
話不多說,上代碼:
??? 1.組件結構:
????????mineStatus:select組件綁定的字段,在tree組件數(shù)據(jù)處理的方法中賦值。
????????multiple:是否多選。
????????mineStatusValue: option組件綁定的數(shù)據(jù)。
????????data:tree組件的數(shù)據(jù)綁定,通過后端將數(shù)據(jù)拿到,再使用遞歸方法將數(shù)據(jù)處理為tree組件所需要的數(shù)據(jù)結構。
????????show-checkbox:節(jié)點是否可被選擇。
????????check-strictly:在顯示復選框的情況下,是否嚴格的遵循父子不互相關聯(lián)的做法。
????????node-key:每個樹節(jié)點用來作為唯一標識的屬性,整棵樹應該是唯一的。
? ? ? ? highlight-current:是否高亮當前選中節(jié)點。
????????props:tree組件的配置選項,一般為一個json對象,里面包含label、children、disabled、isLeaf四個字段。
? ? ? ? check-change:tree組件節(jié)點選中狀態(tài)發(fā)生變化時的回調。
```
<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.數(shù)據(jù)處理:根據(jù)數(shù)據(jù)對選中的值進行賦值,調用搜索的接口方法進行搜索。
????setCheckedNodes:設置目前勾選的節(jié)點,使用此方法必須設置 node-key 屬性。
????getCheckedNodes:若節(jié)點可被選擇(即?show-checkbox?為?true),則返回目前被選中的節(jié)點所組成的數(shù)組。
```
// tree數(shù)據(jù)處理方法
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.遞歸的封裝:處理從后端拿回來的分類數(shù)據(jù),然后將數(shù)據(jù)結構使用遞歸方法處理,轉換成tree組件的所需要的數(shù)據(jù)結構。
```
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;
}
```