是什么为什么怎么做
递归组件就是指组件在模板中调用自己,开启递归组件的必要条件,就是在组件中设置一个 name 选项。
以后天管理的左侧菜单栏为例
代码如下:
// menu/index.vue<template><template v-for="(item, index) in menuList" :key="item.path"><!-- 没有子路由 --><template v-if="!item.children"><el-menu-item v-if="!item.meta.hidden" :index="item.path"><template #title><span>标 </span><span>{{ item.meta.title }}</span></template></el-menu-item></template><!-- 有子路由,但是只有一个 --><template v-if="item.children && item.children.length == 1"><el-menu-item v-if="!item.children[0].meta.hidden" :index="item.children[0].path"><template #title><span>{{ item.children[0].meta.title }}</span></template></el-menu-item></template><!-- 有子路由,且个数大于1个 --><el-sub-menu :index="item.path" v-if="item.children && item.children.length > 1"><template #title><span>{{ item.meta.title }}</span></template><!-- 递归组件 --><Menu :menuList="item.children"></Menu></el-sub-menu></template></template><script lang="ts">import { defineComponent } from 'vue'export default defineComponent({name: 'Menu',})</script><script lang="ts" setup>// 接受父组件传递的全部路由数据defineProps(['menuList'])</script><style lang="scss" scoped></style>
在进行递归组件是,主要使用的是插槽来实现数据的传递。
// layout/index.vue// 样式变量是在style文件中定义的变量<template><div class="layout_container"><!-- 左侧菜单 --><div class="layout_slider"><Logo></Logo><!-- 展示菜单 --><!-- 滚动组件 --><el-scrollbar class="scrollbar"><!-- 菜单组件 --><el-menu background-color="#001529" text-color="#fff"><Menu :menuList="userStore.menuRoutes"></Menu></el-menu></el-scrollbar></div><!-- 顶部导航 --><div class="layout_tabbar">456</div><!-- 内容展示区 --><div class="layout_main"><!-- <p style="height: 3000px">789</p> --></div></div></template><script lang="ts">import { defineComponent } from 'vue'export default defineComponent({name: 'Layout',})</script><script lang="ts" setup>// 引入左侧菜单子组件import Logo from './logo/index.vue'// 引入菜单组件import Menu from './menu/index.vue'// 获取用户相关的小仓库import useUserStore from '@/store/user'const userStore = useUserStore()</script><style lang="scss" scoped>.layout_container {width: 100%;height: 100vh;// background-color: #e84a4a;.layout_slider {width: $base-menu-width;height: 100vh;background-color: $base-menu-background;.scrollbar {width: 100%;height: calc(100vh - $base-menu-logo-height);.el-menu {border-right: none;}}}.layout_tabbar {position: fixed;top: 0px;left: $base-menu-width;width: calc(100% - $base-menu-width);height: $base-tabber-height;background-color: #45c1ea;}.layout_main {position: absolute;width: calc(100% - $base-menu-width);height: calc(100vh - $base-tabber-height);background-color: #48ca62;left: $base-menu-width;top: $base-tabber-height;padding: 20px;overflow: auto;}}</style>
插槽
插槽又分为具名插槽、匿名插槽、自定义插件,经常用于组件的封装
