嵌套路由 - children 选项 - vue router(路由)
嵌套路由
一些应用程序的 UI 由多层嵌套的组件组成。在这种情况下,URL 的片段通常对应于特定的嵌套组件结构,例如:
/user/johnny/profile /user/johnny/posts +------------------+ +-----------------+ | User | | User | | +--------------+ | | +-------------+ | | | Profile | | +------------> | | Posts | | | | | | | | | | | +--------------+ | | +-------------+ | +------------------+ +-----------------+
通过 Vue Router,你可以使用嵌套路由配置来表达这种关系。
接着上节创建的 app:
//HTML
//JS import { createRouter, createWebHistory } from "vue-router"; const User = { template: 'User {{ $route.params.id }}' } const routes = [{ path: '/user/:id', component: User }] const router = createRouter({ history: createWebHistory(), routes, // routes:routes 简写 })
这里的是一个顶层的
router-view
。它渲染顶层路由匹配的组件。同样地,一个被渲染的组件也可以包含自己嵌套的。例如,如果我们在
User
组件的模板内添加一个:
const User = { template: ``, }User {{ $route.params.id }}
要将组件渲染到这个嵌套的router-view
中,我们需要在路由中配置children:
const routes = [ { path: '/user/:id', component: User, children: [ { // 当 /user/:id/profile 匹配成功 // UserProfile 将被渲染到 User 的 内部 path: 'profile', component: UserProfile, }, { // 当 /user/:id/posts 匹配成功 // UserPosts 将被渲染到 User 的 内部 path: 'posts', component: UserPosts, }, ], }, ]
注意,以/
开头的嵌套路径将被视为根路径。这允许你利用组件嵌套,而不必使用嵌套的 URL。
如你所见,children配置只是另一个路由数组,就像routes
本身一样。因此,你可以根据自己的需要,不断地嵌套视图。
此时,按照上面的配置,当你访问/user/eduardo时,在User
的router-view
里面什么都不会呈现,因为没有匹配到嵌套路由。也许你确实想在那里渲染一些东西。在这种情况下,你可以提供一个空的嵌套路径:
const routes = [ { path: '/user/:id', component: User, children: [ // 当 /user/:id 匹配成功 // UserHome 将被渲染到 User 的 内部 { path: '', component: UserHome }, // ...其他子路由 ], }, ]
嵌套的命名路由
在处理命名路由时,你通常会命名子路由:
const routes = [ { path: '/user/:id', component: User, // 请注意,只有子路由具有名称 children: [{ path: '', name: 'user', component: UserHome }], }, ]
这将确保导航到/user/:id
时始终显示嵌套路由。
在一些场景中,你可能希望导航到命名路由而不导航到嵌套路由。例如,你想导航/user/:id
而不显示嵌套路由。那样的话,你还可以命名父路由,但请注意重新加载页面将始终显示嵌套的子路由,因为它被视为指向路径/user/:id
的导航,而不是命名路由:
const routes = [ { path: '/user/:id', name: 'user-parent' component: User, children: [{ path: '', name: 'user', component: UserHome }], }, ]
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)