添加 el-tree
组件到 list.vue
当中,当然你可以直接复制我下方的整体代码
<template>
<div class="app-container">
<el-input v-model="filterText" placeholder="Filter keyword" />
<el-tree
ref="tree2"
:data="data2"
:props="defaultProps"
:filter-node-method="filterNode"
class="filter-tree"
default-expand-all
/>
</div>
</template>
<script>
export default {
name: "list",
data() {
return {
filterText: '',
data2: [{
id: 1,
label: 'Level one 1',
children: [{
id: 4,
label: 'Level two 1-1',
children: [{
id: 9,
label: 'Level three 1-1-1'
}, {
id: 10,
label: 'Level three 1-1-2'
}]
}]
}, {
id: 2,
label: 'Level one 2',
children: [{
id: 5,
label: 'Level two 2-1'
}, {
id: 6,
label: 'Level two 2-2'
}]
}, {
id: 3,
label: 'Level one 3',
children: [{
id: 7,
label: 'Level two 3-1'
}, {
id: 8,
label: 'Level two 3-2'
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
}
},
watch: {
filterText(val) {
this.$refs.tree2.filter(val)
}
},
methods: {
filterNode(value, data) {
if (!value) return true
return data.label.indexOf(value) !== -1
}
}
}
</script>
<style scoped>
</style>
现在去编写后端接口,封装好对应的模型数据返回,渲染即可,在服务器端建立模型
/**
* @author BNTang
* @version S2.3.2Dev
* @program video_parent
* @date Created in 2021/4/4 11:53
* @description 分类管理列表树形数据类模型
**/
public class LevelCategory {
private String id;
private String title;
private List<LevelCategory> children = new ArrayList<>();
}
创建 Controller 处理请求及业务,Controller 层的内容如下
/**
* <p>
* 获取分类列表树形结构
* </p>
*/
("/getTreeCategory")
public ResponseResult getTreeCategory() {
return ResponseResult.ok().data("list", categoryService.getTreeCategory());
}
在实现类当中创建上图中报错的那个方法如下,首先在接口当中添加方法修改 CategoryService.java
/**
* <p>
* 获取分类列表树形结构
* </p>
*
* @return 树形结构分类Data
*/
List<LevelCategory> getTreeCategory();
紧接着就是编写实现类
public List<LevelCategory> getTreeCategory() {
// 1.读取1级分类
QueryWrapper<Category> oneQueryWrapper = new QueryWrapper<>();
oneQueryWrapper.eq("parent_id", 0);
List<Category> oneCategories = baseMapper.selectList(oneQueryWrapper);
// 2.读取2级分类
QueryWrapper<Category> twoQueryWrapper = new QueryWrapper<>();
twoQueryWrapper.ne("parent_id", 0);
List<Category> twoCategories = baseMapper.selectList(twoQueryWrapper);
// 封装模型数据
List<LevelCategory> resultData = new ArrayList<>();
oneCategories.forEach(oneCategory -> {
// 把Category转成LevelCategory
LevelCategory oneLevelCategory = new LevelCategory();
// 属性的复制
// 把前一个对象当中的属性值复制到后一个对象当中相同的属性中去
// 如果前一个对象在后一个对象当中没有找到相同的属性,就不复制
BeanUtils.copyProperties(oneCategory, oneLevelCategory);
// 获取当前子分类有哪些
// 遍历所有的二级分类
twoCategories.forEach(twoCategory -> {
// 二级分类的parent_id=一级分类的id,就是当前一级分类,的子级
if (twoCategory.getParentId().equals(oneCategory.getId())) {
LevelCategory twoLevelCategory = new LevelCategory();
BeanUtils.copyProperties(twoCategory, twoLevelCategory);
oneLevelCategory.getChildren().add(twoLevelCategory);
}
});
resultData.add(oneLevelCategory);
});
return resultData;
}
如果的业务我在代码当中写了注释,大致意思就是把一级二级都查询出来,先遍历一级,转换一级,然后在遍历二级看一下二级的父Id,是否等于一级是的话就是子分类,添加到 Children 当中,重启工程测试接口,效果如下图所示