vue3中router配置中的children怎么用

发布时间 2023-12-19 09:07:01作者: 代码一刀流

在Vue 3中,当你使用Vue Router创建路由配置时,
children属性允许你为某个路由定义嵌套路由。这意味着你可以在父路由下设置子路由,从而构建出具有层级结构的URL路径。
这里是一个基本的例子,展示了如何在Vue Router中使用children属性:

import { createRouter, createWebHistory } from 'vue-router';
import ParentComponent from './components/ParentComponent.vue';
import ChildComponent from './components/ChildComponent.vue';
import AnotherChildComponent from './components/AnotherChildComponent.vue';

const routes = [
  {
    path: '/parent',
    component: ParentComponent,
    children: [
      {
        // 当 /parent/child 被匹配时,ChildComponent 会被渲染在 ParentComponent 的 <router-view> 中
        path: 'child',
        component: ChildComponent,
      },
      {
        // 当 /parent/another-child 被匹配时,AnotherChildComponent 会被渲染在 ParentComponent 的 <router-view> 中
        path: 'another-child',
        component: AnotherChildComponent,
      },
      // 如果你想要一个默认的子路由,可以使用空字符串作为子路由的 path
      {
        path: '',
        component: DefaultChildComponent,
      }
    ],
  },
  // ...其他路由
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

在这个例子中,/parent 路径对应的组件 ParentComponent 有两个子路由:/parent/child 和 /parent/another-child。这些子路由分别对应 ChildComponent 和 AnotherChildComponent 组件。当用户访问这些路径时,对应的子组件将会被渲染在 ParentComponent 的 中。
要使嵌套路由工作,ParentComponent 需要包含一个 元素,这是子组件渲染的占位符:

<!-- ParentComponent.vue -->
<template>
  <div>
    <h1>Parent Component</h1>
    <!-- 子路由的组件将会渲染在这里 -->
    <router-view></router-view>
  </div>
</template>

使用嵌套路由可以帮助你组织和管理复杂的界面布局,特别是当你的应用程序具有多层次的导航结构时。

请不要忘记帮忙点赞,这是对我的最大支持和鼓励,如果你有任何问题或者建议,也欢迎在评论区留言。