vue实现局部路由
Vue 实现局部路由的方法
在 Vue 中实现局部路由(也称为嵌套路由或子路由)可以通过 Vue Router 的嵌套路由功能完成。以下是具体实现方法:
配置嵌套路由
在 Vue Router 的配置文件中,通过 children 属性定义嵌套路由。父路由需要指定一个 <router-view> 用于渲染子路由组件。
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent
}
]
}
]
父组件中放置 <router-view>
父组件需要预留子路由的渲染位置,通常在模板中添加 <router-view> 标签。
<template>
<div>
<h2>父组件</h2>
<router-view></router-view>
</div>
</template>
子路由的访问路径
子路由的路径会自动基于父路由的路径拼接。例如上述配置中,子路由的完整路径为 /parent/child。

动态嵌套路由
如果需要动态路由参数,可以在父路由和子路由中同时使用动态参数。
const routes = [
{
path: '/parent/:id',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent
}
]
}
]
编程式导航
在组件中可以通过 this.$router.push 跳转到嵌套路由。

this.$router.push('/parent/child')
命名路由
可以为嵌套路由命名,方便直接通过名称跳转。
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: 'child',
name: 'childRoute',
component: ChildComponent
}
]
}
]
跳转时使用名称:
this.$router.push({ name: 'childRoute' })
默认子路由
可以设置默认子路由,当访问父路由时自动渲染默认子路由。
const routes = [
{
path: '/parent',
component: ParentComponent,
children: [
{
path: '',
component: DefaultChildComponent
},
{
path: 'child',
component: ChildComponent
}
]
}
]
注意事项
- 嵌套路由的路径是相对于父路由的,不需要以
/开头 - 确保父组件中有
<router-view>用于渲染子组件 - 可以使用路由元信息(meta)为嵌套路由添加额外数据
- 嵌套路由也支持路由守卫,可以在父路由或子路由上定义
通过以上方法可以实现 Vue 中的局部路由功能,适用于需要分层级展示内容的场景。






