vue route 嵌套路由

vue yekong 144℃

在Vue中,嵌套路由(Nested Routes)允许你将组件映射到路由的嵌套路径中。这在构建具有多层嵌套的用户界面时非常有用。使用Vue Router时,你可以在路由配置中使用children数组来定义嵌套路由。

以下是一个嵌套路由的基本示例:

// router.js 或 router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/components/Home.vue';
import User from '@/components/User.vue';
import UserProfile from '@/components/UserProfile.vue';
import UserPosts from '@/components/UserPosts.vue';

Vue.use(Router);

const router = new Router({
  routes: [
    {
      path: '/',
      component: Home
    },
    {
      path: '/user/:id',
      component: User,
      children: [
        {
          // 当匹配到 /user/:id/profile 时
          // UserProfile 将被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
          // 当匹配到 /user/:id/posts 时
          // UserPosts 将被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
});

export default router;

在这个例子中,User组件有两个嵌套路由:UserProfileUserPosts。这意味着当你访问/user/:id/profile时,UserProfile组件将会被渲染在User组件的<router-view>中。同样地,访问/user/:id/posts时,UserPosts组件将会被渲染。

User组件的模板中,你需要包含一个<router-view>元素,这是嵌套路由的出口:

<!-- User.vue -->
<template>
  <div>
    <h1>User {{ $route.params.id }}</h1>
    <!-- 嵌套路由的出口 -->
    <router-view></router-view>
  </div>
</template>

当访问/user/:id的子路径时,对应的子组件(UserProfileUserPosts)将会渲染在User组件的<router-view>中。

喜欢 (0)