组件内容
<template>
<div class="tree-box">
<div
class="tree-box-content"
v-for="nodeItem in data"
:key="nodeItem.code"
>
<div class="notetitle">
<span
class="icon"
@click="childClick(nodeItem)"
v-if="nodeItem.children.length"
>
<i :class="nodeItem.open? 'el-icon-minus' : 'el-icon-plus'" />
</span>
<span @click="childClick(nodeItem)">
<span class="text">{{ nodeItem[title] }}</span>
</span>
</div>
<div
v-if="
nodeItem.children && nodeItem.children.length > 0 && nodeItem.open
"
>
<myTree
:data="nodeItem.children"
:title="title"
:fatherNode="nodeItem"
:value="value"
></myTree>
</div>
</template>
<script>
export default {
name: "myTree",
props: {
// 数据
data: {
type: Array,
},
// 节点展示的标签对象属性键名
title: {
type: String,
default: "title",
},
// 树节点表示的值的键名
value: {
type: String,
default: "value",
},
// 父级节点
fatherNode: {
type: Object,
},
},
methods: {
// 当前组件节点点击事件
childClick(nodeItem) {
nodeItem.open= !nodeItem.open;
// 用于更新节点数据
this.$forceUpdate();
},
}
}
</script>
<style lang='scss' scoped>
.tree-box {
width: 100%;
height: 100%;
overflow-y: auto;
padding-left: 30px;
}
.notetitle {
display: flex;
align-items: center;
font-size: 18px;
line-height: 36px;
}
.text:hover {
color: #fff;
}
</style>
父组件使用
<template>
<div style="width: 400px;height: 700px;">
<myTree :data="data" />
</div>
</template>
<script>
import myTree from "myTree/index.vue";
export default {
components: { myTree },
data(){
data: [
{
open: false,
title: '张三',
code: 1,
children: []
}
],
}
}
</script>
如果后端没给open字段,就自己添加
let a = function (arr) {
for (let i = 0; i < arr.length; i++) {
arr[i].open = false;
if (arr[i].children.length > 0) {
a(arr[i].children);
}
}
};
for (let i = 0; i < this.data.length; i++) {
this.siteList[i].open = false;
a(this.data[i].children);
}