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;
父组件中设置 <router-view>
在父组件(如 Parent.vue)中预留子路由的渲染出口:
<template>
<div>
<h1>父组件</h1>
<router-view></router-view> <!-- 子路由内容将在此渲染 -->
</div>
</template>
子路由跳转方式
-
编程式导航:通过
router.push方法跳转
this.$router.push('/parent/child1'); -
声明式导航:在模板中使用
<router-link><router-link to="/parent/child1">跳转到子路由1</router-link>
动态子路由配置
若需传递参数,可配置动态路由:
{
path: '/parent/:id',
component: Parent,
children: [
{
path: 'child',
component: Child
}
]
}
跳转时传递参数:
this.$router.push('/parent/123/child');
注意事项
- 子路由的
path可以省略/,如path: 'child1'会被解析为/parent/child1。 - 若子路由需默认显示,可设置
path: ''并添加redirect或直接指定默认组件。 - 嵌套路由的层级可以无限扩展,但需合理设计以避免性能问题。






