时间: 2020-08-25|tag:44次围观|0 条评论

实际生活中的应用界面,通常由多层嵌套的组件组合而成。
同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件。
借助 vue-router,使用嵌套路由配置,就可以很简单地表达这种关系。

const router = new VueRouter({  routes: [    { path: '/user/:id', component: User,      children: [        {          // 当 /user/:id/profile 匹配成功,          // UserProfile 会被渲染在 User 的 <router-view> 中          path: 'profile',          component: UserProfile        },        {          // 当 /user/:id/posts 匹配成功          // UserPosts 会被渲染在 User 的 <router-view> 中          path: 'posts',          component: UserPosts        }      ]    }  ]})

要注意,以 / 开头的嵌套路径会被当作根路径。
Vue的官方文档描述如上。
地址:https://router.vuejs.org/zh/guide/essentials/nested-routes.html

操作过程中,具体会遇到以下3种情况:

1、vue文档

const router = new VueRouter({  routes: [    { path: '/home', component: User,      children: [        {          path: 'children1',          component: UserProfile        },        {          path: 'children2',          component: UserPosts        }      ]    }  ]})

XXX/home 路径展示的是User页面
XXX/home/children1 路径展示的是UserProfile页面
XXX/home/children2路径展示的是UserPosts页面

2、如果将子路由的path加斜杠,相当于书写错误

const router = new VueRouter({  routes: [    { path: '/home', component: User,      children: [        {          path: '/children1',          component: UserProfile        },        {          path: '/children2',          component: UserPosts        }      ]    }  ]})

XXX/home 路径展示的是User页面
访问
XXX/home/children1
XXX/home/children2
两个子路径,UserProfile、UserPosts页面展示为空白
因为以 / 开头的嵌套路径会被当作根路径。
只有修改访问地址为
XXX/children1
XXX/children2
才能访问对应页面

3、
还有人加多个斜杠书写为

const router = new VueRouter({  routes: [    { path: '/home', component: User,      children: [        {          path: '/home/children1',          component: UserProfile        },        {          path: '/home/children2',          component: UserPosts        }      ]    }  ]})

这样在子路由里写完整路径,同样可以访问
XXX/home 展示User页面
XXX/home/children1 展示UserProfile页面
XXX/home/children2展示的UserPosts页面

综上,使用第一种写法更为规范方便。

文章转载于:https://www.jianshu.com/p/5a9a798f0959

原著是一个有趣的人,若有侵权,请通知删除

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《2、vue子路由
   

还没有人抢沙发呢~