遇到那种嵌套层数不知道的数据 很头疼的,目前为了解决头疼的方法就是vue组件递归方法。说白了就是自己调用自己。下面的案例是vue3语法环境,复制粘贴可以在调整到vue2的环境,代码直接复制使用。
child.vue
<template>
<div :style="{paddingLeft: level * 20 + 'px' }">
<div class="Title">{{ options.title }}</div>
<child class="children" v-for="(item,index) in options.children" :index="index" :level="level + 1"
:options="item"></child>
</div>
</template>
<script setup>
const props = defineProps({
index: {
type: Number,
default: 0,
},
level: {
type: Number,
default: 0,
},
options: {
type: Object,
default: () => {
return {
children: []
}
}
}
})
</script>
<style lang="less" scoped>
</style>
parent.vue
<template>
<childVue v-for="(item,index) in Treelist" :options="item" :level="0" />
</template>
<script setup>
import { ref } from 'vue';
import childVue from './child.vue';
const Treelist = ref([{
title: 'A', children: [
{ title: 'A-A', children: [{ title: 'A-A-A', children: [] }, { title: 'A-A-B', children: [] }, { title: 'A-A-C', children: [] },] },
{ title: 'A-B', children: [{ title: 'A-B-A', children: [] }, { title: 'A-B-B', children: [] }, { title: 'A-B-C', children: [] },] },
{ title: 'A-C', children: [{ title: 'A-C-A', children: [] }, { title: 'A-C-B', children: [] }, { title: 'A-C-C', children: [] },] },
]
}, {
title: 'B', children: [
{ title: 'B-A', children: [{ title: 'B-A-A', children: [] }, { title: 'B-A-B', children: [] }, { title: 'B-A-C', children: [] },] },
{ title: 'B-B', children: [{ title: 'B-B-A', children: [] }, { title: 'B-B-B', children: [] }, { title: 'B-B-C', children: [] },] },
{ title: 'B-C', children: [{ title: 'B-C-A', children: [] }, { title: 'B-C-B', children: [] }, { title: 'B-C-C', children: [] },] }
]
}]);
</script>
<style lang="less" scoped>
</style>