关于 router-view-slot

关于 router-view-slot

App.vue
<template>
    <router-view>router-view>
template>
配置动态路由
import layout from "@/layout/index.vue";
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: "/",
            name: "layout",
            redirect: "/dashboard",
            component: layout,
        },
    ]
});
const routes = [
    {
        path: "/help-center",
        name: "helpCenter",
        meta: {
            title: "帮助中心",
        },
        component: () => import("@/views/HelpCenter.vue"),
    },
    {
        path: "/dashboard",
        name: "dashboard",
        meta: {
            title: "仪表盘",
        },
        component: () => import("@/views/Dashboard.vue"),
    },
    {
        path: "/analytics",
        name: "analytics",
        meta: {
            title: "数据分析",
        },
        component: () => import("@/views/Analytics.vue"),
    },
    {
        path: "/user-profile",
        name: "userProfile",
        meta: {
            title: "用户资料",
        },
        component: () => import("@/views/Profile.vue"),
    },
    {
        path: "/project-management",
        name: "projectManagement",
        meta: {
            title: "项目管理",
        },
        component: () => import("@/views/Management.vue"),
    },
];

routes.forEach((v) => router.addRoute("layout", v));

export default router;

添加嵌套路由,这里为 layout 添加子路由,
addRoute("layout", v)) 相当于

router.addRoute({
    name: "layout",
    path: "/layout",
    component: layout,
    children: [{ path: "/help-center", component: () => import("@/views/HelpCenter.vue") }],
});
layout.vue
<template>
    <div class="layout">
        <div class="left">
            <div
                v-for="(item, index) in routes"
                :key="index">
                <div>
                    <router-link :to="item.path">
                        {{ item?.meta?.title || "首页" }}
                    </router-link>
                </div>
            </div>
        </div>
        <div class="right">
            <router-view v-slot="{ Component }">
                <component
                    :is="Component"
                    :key="route.path" />
            </router-view>
        </div>
    </div>
</template>

<script lang="ts" setup>
    import { useRoute, useRouter } from "vue-router";
    const route = useRoute();
    const router = useRouter();
    const routes = router.getRoutes();
</script>

使用 router-view v-slot 进行动态展示,transitionkeep-alive 现在必须通过 v-slot 在 RouterView 内部使用

<router-view v-slot="{ Component }">
  <transition>
    <keep-alive>
      <component :is="Component" />
    keep-alive>
  transition>
router-view>

链接: router-view-keep-alive-transitions.md

你可能感兴趣的:(前端,javascript,开发语言)