效果
前端
<template><div class="app-container"><el-inputplaceholder="输入关键字进行过滤"、<! -- 双向绑定-- >v-model="filterText"></el-input><el-tree ref="tree":data="subjectList" :props="defaultProps" :filter-node-method="filterNode"></el-tree></div>
</template><script>
import subjectApi from '@/Api/edu/Subject'export default {data(){return {filterText:"",subjectList:[],// Tree 组件 显示的值绑定 defaultProps:{children:'children',label:'title'}}}, watch: { // 监听器filterText(val) {// 对树节点进行筛选操作 接收一个任意类型的参数,该参数会在 filter-node-method 中作为第一个参数this.$refs.tree.filter(val);}},created(){this.fetchNodeList()},methods:{fetchNodeList(){subjectApi.getNestedTreeList().then(response=>{this.subjectList = response.data.items})},filterNode(value, data) {if (!value) return true;//console.log(data)// 过滤出节点return data.title.toLowerCase().indexOf(value.toLowerCase()) !== -1;//console.log(value)}}
}
</script><style></style>
在组件创建时,我们向后端发起请求获取树形列表的数据,然后设置绑定的结构, 并且将列表绑定到tree
// Tree 组件 显示的值绑定 defaultProps:{children:'children',label:'title'}
<el-tree <! -- 绑定元素 这样就可以通过this.$refs.tree 访问到该元素对象-- >ref="tree"<! -- 数据绑定-- >:data="subjectList" <! -- 数据结构绑定-- >:props="defaultProps" :filter-node-method="filterNode"></el-tree>
后端
// controller
@ApiOperation("嵌套数据列表")@GetMapping("nestedlist")public ResultVo nestedList(){List<SubjectVo> subjectVos= subjectService.nestedList();return ResultVo.ok().data("items",subjectVos);}
SubjectVo
import lombok.Data;import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;/*** Created with IntelliJ IDEA.** @Auther: zlf* @Date: 2021/04/11/21:59* @Description:*/
@Data
public class SubjectVo implements Serializable {private static final long serialVersionUID = 1L;private String id;private String title;private String sort;private List<SubjectVo> children = new ArrayList<>();
}
mapper接口
@Repository
public interface SubjectMapper extends BaseMapper<Subject> {List<SubjectVo> selectNestedListByParentId(String id);}
mapper 接口的实现
<resultMap id="nestedSubject" type="com.zlf.edu.entity.vo.SubjectVo"><id property="id" column="id" /><result property="title" column="title" /><result property="sort" column="sort" /><collection property="children"column="id"select="selectNestedListByParentId"ofType="com.zlf.edu.entity.vo.SubjectVo"/></resultMap><select id="selectNestedListByParentId" resultMap="nestedSubject" parameterType="String">select id ,sort,title from edu_subject where parent_id = #{parentid}</select>