1
我的数据:
let data = [
    {
        title: 1,
        children: [
            {
                title: 1.1,
                children: [
                    {
                        title: 1.3
                    }
                ]
            }
        ]
    },
    {
        title: 2,
        children: [
            {
                title: 2.1,
                children: [
                    {
                        title: 2.1.1,
                        children: [
                            {
                                title: 2.1.1.1
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
  • 大概就像这样的数据格式,递归层级有多深,不知道..
<template v-for="item in data">
    <a-sub-menu :key="item.title">
        <span slot="title">
            <span>{{item.title}}</span>
        </span>
        <template v-for="c in item.children">
            <a-menu-item :key="c.title">{{c.title}}</a-menu-item>
        </template>
    </a-sub-menu>
</template>
  • 如果还有children就要创建<a-sub-menu>,我现在只写到这写不下去了...求帮忙
5月29日提问
1 个回答
1

已采纳

vue递归主要靠组件调用自身。如:

SubMenu.vue

<template>
    <div>
        <span>{{menu.title}}</span>

        <template v-if="menu.children && menu.children.length">
            <template v-for="cmenu in menu.children">
                <SubMenu :key="cmenu.title" :menu="cmenu" />
            </template>
        </template>
    </div>
</template>

<script>
export default {
    name: 'SubMenu',
    props: {
        menu: {
            type: Object,
            required: true
        }
    }
}
</script>

index.vue

<template>
    <div>
        <template v-for="menu in menus">
            <SubMenu :key="menu.title" :menu="menu" />
        </template>
    </div>
</template>

<script>
export default {
    name: 'Other',
    data(){
        return {
            menus: [
                {
                    title: "a",
                    children: [
                        {
                            title: "a1"
                        },
                        {
                            title: "a2"
                        }
                    ]
                },
                {
                    title: "b",
                    children: [
                        {
                            title: "b1"
                        }
                    ]
                }
            ]
        }
    },
    components: {
        SubMenu: () => import("./components/SubMenu")
    }
}
</script>

撰写答案

推广链接