前端
1.subject.js
import request from '@/utils/request' export default { //1 课程分类列表 getSubjectList() { return request({ url: '/eduservice/edu-subject/getAllSubject', method: 'get' }) } }
2.list.vue
<template> <div class="app-container"> <el-input v-model="filterText" placeholder="Filter keyword" style="margin-bottom:30px;" /> <el-tree ref="tree2" :data="data2" :props="defaultProps" :filter-node-method="filterNode" class="filter-tree" default-expand-all /> </div> </template> <script> import subject from '@/api/subject/subject' export default { data() { return { filterText: '', data2: [], //返回所有分类数据 defaultProps: { children: 'children', label: 'title' } } }, created() { this.getAllSubjectList() }, watch: { filterText(val) { this.$refs.tree2.filter(val) } }, methods: { getAllSubjectList() { subject.getSubjectList() .then(response => { this.data2 = response.data.items }) }, filterNode(value, data) { if (!value) return true return data.title.toLowerCase().indexOf(value.toLowerCase()) !== -1 } } } </script>
2.后端
controller
@GetMapping("getAllSubject") public R nestedList(){ List<OneSubject> subjectNestedVoList = eduSubjectService.nestedList(); return R.OK().data("items", subjectNestedVoList); }
service
List<OneSubject> nestedList();
serviceimpl
public List<OneSubject> nestedList() { //1 查询所有一级分类 parentid = 0 QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>(); wrapperOne.eq("parent_id","0"); List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne); //2 查询所有二级分类 parentid != 0 QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>(); wrapperTwo.ne("parent_id","0"); List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo); //创建list集合,用于存储最终封装数据 List<OneSubject> finalSubjectList = new ArrayList<>(); //3 封装一级分类 //查询出来所有的一级分类list集合遍历,得到每个一级分类对象,获取每个一级分类对象值, //封装到要求的list集合里面 List<OneSubject> finalSubjectList for (int i = 0; i < oneSubjectList.size(); i++) { //遍历oneSubjectList集合 //得到oneSubjectList每个eduSubject对象 EduSubject eduSubject = oneSubjectList.get(i); //把eduSubject里面值获取出来,放到OneSubject对象里面 OneSubject oneSubject = new OneSubject(); // oneSubject.setId(eduSubject.getId()); // oneSubject.setTitle(eduSubject.getTitle()); //eduSubject值复制到对应oneSubject对象里面 BeanUtils.copyProperties(eduSubject,oneSubject); //多个OneSubject放到finalSubjectList里面 finalSubjectList.add(oneSubject); //在一级分类循环遍历查询所有的二级分类 //创建list集合封装每个一级分类的二级分类 List<TwoSubject> twoFinalSubjectList = new ArrayList<>(); //遍历二级分类list集合 for (int m = 0; m < twoSubjectList.size(); m++) { //获取每个二级分类 EduSubject tSubject = twoSubjectList.get(m); //判断二级分类parentid和一级分类id是否一样 if(tSubject.getParentId().equals(eduSubject.getId())) { //把tSubject值复制到TwoSubject里面,放到twoFinalSubjectList里面 TwoSubject twoSubject = new TwoSubject(); BeanUtils.copyProperties(tSubject,twoSubject); twoFinalSubjectList.add(twoSubject); } } //把一级下面所有二级分类放到一级分类里面 oneSubject.setChildren(twoFinalSubjectList); } return finalSubjectList; }
最终测试