//listview组件 递归的组件
<template>
<div>
<div class="list-item" v-for="(item, index) in list" :key="index">
<div class="item-name" :style="item.style">
<slot :name="item.value" :scope="item">{{ item.name }}</slot>
</div>
<div v-if="item.children" class="children-item">
<listview :list="item.children">
//这里是主要解决递归组件失效的问题
<template
v-for="(item1, index1) in Object.keys($slots)"
:key="index1"
v-slot:[item1]
>
//scope是插槽传递的数据
<slot :name="item1" :scope="getScopeData(item1, list)" />
</template>
</listview>
</div>
</div>
</div>
</template>
<script setup name="listview">
import listview from "./index.vue";
const props = defineProps({
list: {
type: Array,
default: () => [],
},
});
const getScopeData = (name, data) => {
const findItem = (name, data) => {
for (const item of data) {
if (item.value === name) {
return item;
}
if (item.children && item.children.length) {
const result = findItem(name, item.children);
if (result) {
return result;
}
}
}
return null;
};
const scope = findItem(name, data);
return scope;
};
</script>
//父组件
<listview :list="list">
<template #jingji="{ scope }">
<div>{{ `${scope.name}插槽` }}</div>
</template>
<template #rujia="{ scope }">
123==={{ scope.name }}
</template>
<template #qitian="{ scope }">
123==={{ scope.name }}
</template>
<template #rujia-1="{ scope }">
123==={{ scope.name }}
</template>
</listview>
import listview from "@/components/listview";
const list = [
{
name: "经济",
value: "jingji",
id: "1",
children: [
{
name: "如家",
value: "rujia",
style: "margin-left: 10px;",
id: "1-1",
children: [
{
style: "margin-left: 20px;",
name: "上江路-如家",
value: "rujia-1",
id: "1-1-1",
children: [
{
style: "margin-left: 30px;",
name: "上江路-如家-3",
id: "1-1-1-1",
value: "rujia-2",
},
],
},
{
style: "margin-left: 20px;",
name: "望江路-如家",
id: "1-1-2",
},
],
},
{
name: "7天",
id: "1-2",
value: "qitian",
style: "margin-left: 10px;",
children: [
{
name: "长江路-7天",
style: "margin-left: 20px;",
id: "1-2-1",
},
{
name: "望江路-7天",
style: "margin-left: 20px;",
id: "1-2-2",
},
],
},
],
},
];