嵌套(多级)路由
嵌套路由就是在路由里面继续加一个新的路由。也叫多级路由,其实就是套娃
在开发中,很少会套到六层路由,一般到达 4 或 5 层路由已经达到极限了,明白了路由的规律,不管套多少层都是一样的,下面演示二级路由
1 配置多级路由(childen)
如下图所示,目前都是一级路由
如果想要配置多级路由,继续在路由里面配置即可
这里要用到 children 配置项,它的值是一个数组,因为这个一级路由可能有 n 多个子路由
children 里面的 path 不需要加杠了,底层遍历的时候会自动加入
// 该文件专门用于创建整个应用的路由器
// 引入路由器import VueRouter from "vue-router";// 引入组件import Abotu from '../pages/About.vue'import Home from '../pages/Home.vue'import News from '../pages/News.vue'import Message from '../pages/Message.vue'// 创建并且暴露文件一个路由器export default new VueRouter({ // 配置路由 本质是一个数组,在里面配置多组路由,每一个路由都是一个key和value映射对象 routes:[ { path:'/about', component:Abotu }, { path:'/home', component:Home, //配置子路由 children:[ // 第一个子路由 { // 此时path不需要加杠了,底层遍历的时候会自动加入 path:'news', component:News }, // 第二个子路由 { path:'message', component:Message } ] }, ] })
复制代码
2 使用多级路由
配置完多级路由之后,使用的必须把一级路由和二级路由完整的路径写到 to 属性中
3 总结
1 配置路由规则,使用 children 配置项:
routes:[ { path:'/about', component:About, }, { path:'/home', component:Home, children:[ //通过children配置子级路由 { path:'news', //此处一定不要写:/news component:News }, { path:'message',//此处一定不要写:/message component:Message } ] }]
复制代码
2 跳转(要写完整路径):
<router-link to="/home/news">News</router-link>
复制代码
评论