素材巴巴 > 程序开发 >

Vue实战(七):实现树形下拉选择

程序开发 2023-09-16 08:48:56

Vue实战(七):实现树形下拉选择

要求:根据用户需求,将年级下面的班级信息以下拉的形式进行选择。

1、安装依赖

npm install @riophae/vue-treeselect --save
 

2、在使用的组件进行引入

import Treeselect from "@riophae/vue-treeselect";
 import "@riophae/vue-treeselect/dist/vue-treeselect.css";
 

3、注册下拉组件

components:{Treeselect
 }
 

4、在组件中使用


 

注意:该组件中的数据格式跟树形结构数据类似,因此我们需要对后端传过来的数据进行处理。

5、接收后端传过来的数据

let data = [{ id: 1, name: "一年级" },{ id: 2, parent_id: 1, name: "一年级1班" },{ id: 3, parent_id: 1, name: "一年级2班" },{ id: 4, name: "二年级" },{ id: 5, parent_id: 4, name: "二年级1班" },{ id: 6, parent_id: 4, name: "二年级2班" },
 ]
 

6、将传过来的数据转换为想要的格式数据

let data = [{ id: 1, name: "一年级" },{ id: 2, parent_id: 1, name: "一年级1班" },{ id: 3, parent_id: 1, name: "一年级2班" },{ id: 4, name: "二年级" },{ id: 5, parent_id: 4, name: "二年级1班" },{ id: 6, parent_id: 4, name: "二年级2班" },
 ];
 data = data.map((item)=>{return{id: item.id,parent_id: item.parent_id,label: item.name}
 })
 
结果为:
 let data = [{ id: 1, label: "一年级" },{ id: 2, parent_id: 1, label: "一年级1班" },{ id: 3, parent_id: 1, label: "一年级2班" },{ id: 4, name: "二年级" },{ id: 5, parent_id: 4, label: "二年级1班" },{ id: 6, parent_id: 4, label: "二年级2班" },
 ]
 

7、再将其转换为树形结构化数据

//将平铺数据转换为树形结构数据getTrees(list, parent_id = 0) {let parentObj = {};list.forEach((o) => {parentObj[o.id] = o;});if (!parent_id) {return list.filter((o) => !parentObj[o.parent_id]).map((o) => ((o.children = this.getTrees(list, o.id)), o));} else {return list.filter((o) => o.parent_id == parent_id).map((o) => ((o.children = this.getTrees(list, o.id)), o));}},
 
最终的数据结构为:
 let data = [{"id":1,"label":"一年级","children":[{"id":2,"parent_id":1,"label":"一年级1班","children":[]},{"id":3,"parent_id":1,"label":"一年级2班","children":[]}]},{"id":4,"label":"二年级","children":[{"id":5,"parent_id":4,"label":"二年级1班","children":[]},{"id":6,"parent_id":4,"label":"二年级2班","children":[]}]}
 ]
 

8、去除树形结构数据中的空children

//去除转换树形结构数据后存在的空childrendeleteChildren(arr) {let childs = arr;for (let i = childs.length; i--; i > 0) {if (childs[i].children) {if (childs[i].children.length) {this.deleteChildren(childs[i].children);} else {delete childs[i].children;}}}return arr;}
 

9、最后的效果图

在这里插入图片描述

在这里插入图片描述

9、完整版代码


 
 

标签:

上一篇: Spark On YARN时指定Python版本 下一篇:
素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。