Vue面试题46:在什么场景下要使用嵌套路由?(总结自B站up主‘前端杨村长’视频,仅供自用学习)
-
分析
- 应用的有些界面是由多层级组件组合而来的,这种情况下,url各部分通常对应某个嵌套的组件,这时就可以通过vue-router的嵌套路由配置来表达这种关系
-
思路
- 概念和使用场景;
- 使用方式;
- 实现原理;
-
回答范例
- 平时开发中,应用的有些界面是由多层级组件组合而来的,这种情况下,url各部分通常对应某个嵌套的组件,vue-router中可以使用嵌套路由配置来表达这种关系;
- 表现形式是在两个路由间切换时,它们有公用的视图内容。此时通常提取一个父组件,内部需要变更的位置放上
<router-view>
,从而形成物理上的嵌套,和逻辑上的嵌套对应起来,即定义嵌套路由时使用children
属性组织嵌套关系; - 原理上是在router-view组件内部判断其所处嵌套层级的深度,将这个深度作为匹配组件数组matched的索引,进而获取对应渲染组件并将其渲染;
-
原理
- router-view获取自己所在的深度:默认0,加1之后传给后代,同时根据深度获取匹配路由:
-
//源码 const injectedDepth = inject(viewDepthKey, 0) // The depth changes based on empty components option, which allows passthrough routes e.g. routes with children // that are used to reuse the `path` property const depth = computed<number>(() => { let initialDepth = unref(injectedDepth) const { matched } = routeToDisplay.value let matchedRoute: RouteLocationMatched | undefined while ( (matchedRoute = matched[initialDepth]) && !matchedRoute.components ) { initialDepth++ } return initialDepth }) const matchedRouteRef = computed<RouteLocationMatched | undefined>( () => routeToDisplay.value.matched[depth.value] ) provide( viewDepthKey, computed(() => depth.value + 1) )