树状结构 Element ui
https://element.eleme.cn/#/zh-CN/component/tree
html
<el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
html
<script>
export default {
data() {
return {
data: [{
label: '一级 1',
children: [{
label: '二级 1-1',
children: [{
label: '三级 1-1-1'
}]
}]
}, {
label: '一级 2',
children: [{
label: '二级 2-1',
children: [{
label: '三级 2-1-1'
}]
}, {
label: '二级 2-2',
children: [{
label: '三级 2-2-1'
}]
}]
}, {
label: '一级 3',
children: [{
label: '二级 3-1',
children: [{
label: '三级 3-1-1'
}]
}, {
label: '二级 3-2',
children: [{
label: '三级 3-2-1'
}]
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
};
},
methods: {
handleNodeClick(data) {
console.log(data);
}
}
};
</script>
加入关键字进行过滤 和 数据渲染
html
<el-input
placeholder="输入关键字进行过滤"
v-model="filterText">
</el-input>
<el-tree
class="filter-tree"
:data="data"
show-checkbox
:props="defaultProps"
accordion
:filter-node-method="filterNode"
ref="tree"
@node-click="handleNodeClick">
</el-tree>
js
watch: {
filterText(val) {
this.$refs.tree.filter(val);
}
},
created() {
this.load_data()
},
mounted(){
},//钩子函数,一般在初始化页面完成后,再对dom节点进行相关操作
methods:{
load_data(){
const _this = this;
axios({
method:"get",
url:"http://localhost:8089/tree/list",
}).then(resp=>{
_this.data = resp.data
});
},
handleNodeClick(data) {
console.log(data.label);
this.label = data.label
},
filterNode(value, data){
if (!value) return true;
return data.label.indexOf(value) !== -1;
}
},
data(){
return {
label: "你好",
filterText: '',
data:[],
defaultProps: {
children: 'children',
label: 'label'
}
}
}
})
java Calss
java
package com.zhan;
import cn.hutool.json.JSONUtil;
import com.zhan.pojo.vo.TreeKnowledgePoints;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SpringBootTest
public class Tree {
private static List<TreeKnowledgePoints> treeKnowledgePoints;
@Test
void Test(){
TreeKnowledgePoints points = new TreeKnowledgePoints(1,0,"操作系统引论");
TreeKnowledgePoints points1 = new TreeKnowledgePoints(2,1,"操作系统作用和目标");
TreeKnowledgePoints points2 = new TreeKnowledgePoints(3,2,"操作系统作用");
TreeKnowledgePoints points3 = new TreeKnowledgePoints(4,2,"操作系统目标");
treeKnowledgePoints = new ArrayList<TreeKnowledgePoints>();
treeKnowledgePoints.add(points);
treeKnowledgePoints.add(points1);
treeKnowledgePoints.add(points2);
treeKnowledgePoints.add(points3);
List<TreeKnowledgePoints> list = buildTree(treeKnowledgePoints,0);
System.out.println(JSONUtil.toJsonStr(list));
}
/**
* 递归
* @param deptList
* @param pid
* @return
*/
private static List<TreeKnowledgePoints> buildTree(List<TreeKnowledgePoints> deptList,int pid){
List<TreeKnowledgePoints> treeList = new ArrayList<TreeKnowledgePoints>();
for (TreeKnowledgePoints dept : deptList) {
if (dept.getParentId() == pid) {
dept.setChildren(buildTree(deptList, dept.getId()));
treeList.add(dept);
}
}
return treeList;
}
}