当前位置:首页 > VUE

vue子路由如何实现

2026-02-24 08:29:22VUE

Vue 子路由实现方法

在 Vue 项目中,子路由(嵌套路由)可以通过 Vue Router 的 children 配置实现。以下是具体步骤:

配置路由文件

在路由配置文件(通常是 router/index.js)中,通过 children 属性定义子路由。父路由需要指定一个 <router-view> 用于渲染子路由组件。

vue子路由如何实现

import { createRouter, createWebHistory } from 'vue-router'
import ParentComponent from '../views/ParentComponent.vue'
import ChildComponent1 from '../views/ChildComponent1.vue'
import ChildComponent2 from '../views/ChildComponent2.vue'

const routes = [
  {
    path: '/parent',
    component: ParentComponent,
    children: [
      {
        path: 'child1',
        component: ChildComponent1
      },
      {
        path: 'child2',
        component: ChildComponent2
      }
    ]
  }
]

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

export default router

父组件中添加 <router-view>

在父组件模板中,添加 <router-view> 作为子路由的出口。

<!-- ParentComponent.vue -->
<template>
  <div>
    <h2>父组件</h2>
    <router-view></router-view>
  </div>
</template>

子路由导航

在父组件或其它地方,可以通过 <router-link> 或编程式导航跳转到子路由。

vue子路由如何实现

<router-link to="/parent/child1">子路由1</router-link>
<router-link to="/parent/child2">子路由2</router-link>

默认子路由

如果需要设置默认子路由,可以通过 redirect 或空路径实现。

{
  path: '/parent',
  component: ParentComponent,
  children: [
    {
      path: '',
      component: DefaultChildComponent
    },
    {
      path: 'child1',
      component: ChildComponent1
    }
  ]
}

动态子路由

子路由也支持动态路径参数。

{
  path: '/parent/:id',
  component: ParentComponent,
  children: [
    {
      path: 'child',
      component: ChildComponent
    }
  ]
}

通过以上方法,可以轻松实现 Vue 中的子路由功能。

分享给朋友:

相关文章

vue项目如何实现

vue项目如何实现

Vue项目实现步骤 环境搭建 确保已安装Node.js和npm。使用Vue CLI创建项目: npm install -g @vue/cli vue create my-project cd my-…

vue如何实现冒泡

vue如何实现冒泡

Vue 实现冒泡排序的步骤 在 Vue 中实现冒泡排序,可以通过数据绑定和计算属性来动态展示排序过程。以下是一个完整的实现示例。 示例代码 <template> <div>…

php如何实现直播

php如何实现直播

实现直播功能的方法 PHP可以通过结合其他技术和工具来实现直播功能。以下是几种常见的方法: 使用流媒体服务器 配置流媒体服务器如Nginx-RTMP、Red5或Wowza。这些服务器支持RTMP协…

vue路由实现iframe

vue路由实现iframe

Vue 路由实现 iframe 的方法 在 Vue 项目中,可以通过路由配置和组件的方式实现 iframe 的嵌入。以下是具体实现步骤: 创建 iframe 组件 新建一个 Vue 组件用于承载 i…

vue如何实现单选

vue如何实现单选

使用原生 HTML 单选按钮 在 Vue 中可以直接使用 HTML 的原生单选按钮,通过 v-model 绑定数据。 <template> <div>…

vue如何实现ifream

vue如何实现ifream

Vue 中实现 iframe 的方法 在 Vue 中可以通过多种方式实现 iframe 的嵌入和控制。以下是几种常见的方法: 使用 HTML 原生 iframe 标签 在 Vue 模板中直接使用…