在Vue中,递归数据,并循环至template,请问要怎么做,主要是条件那块..不明白

我的数据:
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.7k
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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题