前言
最近接到一个需求:要求实现一个树形结构模板,且层级不确定,有多有少,使用vant组件库也没有现成组件,诶!还是自己手动实现一个吧。
一、树形结构
层层数据结构相似或相同,层层嵌套
二、实现步骤
1.数据
这里数据我用到reactive来定义数据,给出数据类似这样:
const state = reactive({
tree : [
{title:'1',
children:[{
title:'1-1',
children:[
{title:'1-1-1',children:[]},
{title:'1-1-2',children:[]}]
},
{
title:'1-2',
children:[{
title:'1-2-1',children:[]
},{
title:'1-2-2',children:[]
}]
}
]
},
{title:'2',
children:[{
title:'2-1',children:[{
title:'2-1-1',children:[]
},{
title:'2-1-2',children:[]
}]
}]
},
]
})
2.渲染
这里渲染的时候写成组件,后期使用方便,即拿即用。
1.父组件
2.子组件
(1)父组件
引入子组件
import Tree from './components/tree.vue'
渲染子组件并传值给子组件
<div class='container'>
<Tree :treeDatas="state.tree" />
</div>
(2)子组件
接受父组件传来的值,这里有多种写法,与vue2基本一样
const props = defineProps({
treeDatas:{
type:Array,
default:[]
}
})
渲染页面,用template包裹递归遍历循环,如果还有子集,将继续循环渲染,
<ul>
<li v-for="node in treeDatas" :key="node.title">
<span>{{ node.title }}</span>
<template v-if="node.children && node.children.length>0">
<Tree :treeDatas="node.children" />
</template>
</li>
</ul>
2.页面展示
最后呈现效果
总结
简单的一个树状结构就实现了,具体真正的的数据结构是什么样子的可自行处理数据再去渲染