vue实现子路由
Vue 实现子路由的方法
在 Vue 中实现子路由主要通过 Vue Router 完成,以下是具体实现步骤:
安装 Vue Router
确保项目中已安装 Vue Router,若未安装,可以通过以下命令安装:
npm install vue-router
配置路由文件
在项目的 src/router/index.js 文件中配置路由,定义父路由和子路由:

import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{
path: '/parent',
component: () => import('@/views/Parent.vue'),
children: [
{
path: 'child1',
component: () => import('@/views/Child1.vue')
},
{
path: 'child2',
component: () => import('@/views/Child2.vue')
}
]
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
父组件中设置路由出口
在父组件 Parent.vue 中,使用 <router-view> 作为子路由的出口:
<template>
<div>
<h1>父组件</h1>
<router-link to="/parent/child1">子路由1</router-link>
<router-link to="/parent/child2">子路由2</router-link>
<router-view></router-view>
</div>
</template>
子路由组件
创建子路由对应的组件文件(如 Child1.vue 和 Child2.vue),内容根据需求编写:

<template>
<div>
<h2>子路由1</h2>
</div>
</template>
动态子路由
若需要动态子路由,可以在子路由的 path 中使用参数:
children: [
{
path: 'child/:id',
component: () => import('@/views/Child.vue')
}
]
路由跳转
在代码中通过 router.push 跳转子路由:
this.$router.push('/parent/child1');
嵌套路由命名
可以为子路由命名,便于跳转:
children: [
{
path: 'child1',
name: 'Child1',
component: () => import('@/views/Child1.vue')
}
]
通过以上步骤,可以在 Vue 中实现子路由功能。






