一、前言
嵌套路由是一个很常见的功能
- 比如在home页面中, 我们希望通过/home/news和/home/message访问一些内容.
- 一个路径映射一个组件, 访问这两个路径也会分别渲染两个组件.
二、使用步骤
实现嵌套路由有两个步骤:
- 创建对应的子组件, 并且在路由映射中配置对应的子路由
- 在组件内部使用
<router-view>
标签
1、创建两个子路由对应的组件
2、要在嵌套的出口中渲染组件,需要在 VueRouter 的参数中使用 children
配置
children 配置就像 routes 配置一样,是一个数组,所以也可以嵌套多层路由。
注意:以 /
开头的嵌套路径会被当作根路径,所以子路由上不用加 /
。在生成路由时,主路由上的path会被自动添加到子路由之前,所以子路由上的path不用在重新声明主路由上的path了。
//配置路由的信息
import Vue from 'vue'
import Router from 'vue-router'
//路由懒加载
const Home = () => import('../components/Home')
const HomeMessage = () => import('../components/HomeMessage')
const HomeNews = () => import('../components/HomeNews')
Vue.use(Router)
const routes = [
{
path:'',
redirect:'/home'
},
{
path: '/home',
component: Home,
children:[
{
path:'news', //嵌套路由的时候,路径前边不能加 /
component:HomeNews
},
{
path:'message',
component: HomeMessage
}
]
}
]
const router = new Router({
routes
});
export default router
3、在Home组件中使用
//Home.vue文件
<template>
<div>
<h2 class="title">我是首页Home</h2>
//注意这里的路径必须是完整的
<router-link to="/home/news">新闻</router-link>
<router-link to="/home/message">消息</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "Home"
}
</script>
<style scoped>
</style>
此时,基于上面的配置,当你访问 /home 时,router-view是不会渲染任何东西,这是因为没有匹配到合适的子路由。如果你想要渲染点什么,可以提供一个 空的子路由
const router = new VueRouter({
routes: [
{
path: '/home',
component: Home,
children: [
// 当 /home 匹配成功,
// HomeNews会被渲染在 Home的 <router-view> 中
// { path:'', redirect:'news'},使用重定向
{ path: '', component: HomeNews},
// ...其他子路由
]
}
]
})
三、资料
前端学习交流QQ群,群内学习讨论的氛围很好,大佬云集,期待您的加入:862748629 点击加入