Skip to content

Commit 7474fcb

Browse files
committed
feat(BetterRouterView): 添加 exact 属性
- 新增 `exact` 属性,用于控制是否只渲染精确匹配的视图组件
1 parent 18436ec commit 7474fcb

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/BetterRouterView.ts

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,17 @@ import type {
1111
RouteLocationNormalizedLoadedGeneric,
1212
RouterViewProps,
1313
} from 'vue-router'
14-
import { defineComponent, getCurrentInstance, h, shallowRef } from 'vue'
15-
import { RouterView } from 'vue-router'
14+
import {
15+
computed,
16+
defineComponent,
17+
getCurrentInstance,
18+
h,
19+
inject,
20+
provide,
21+
shallowRef,
22+
toValue,
23+
} from 'vue'
24+
import { RouterView, useRoute, viewDepthKey } from 'vue-router'
1625
import { getWrappers } from './wrappers'
1726

1827
export interface SlotData {
@@ -26,6 +35,7 @@ export type ResolveViewKey = (
2635

2736
export interface BetterRouterViewProps extends RouterViewProps {
2837
resolveViewKey?: ResolveViewKey
38+
exact?: boolean
2939
}
3040

3141
export const BetterRouterView: new () => {
@@ -40,6 +50,9 @@ export const BetterRouterView: new () => {
4050
resolveViewKey: {
4151
type: Function,
4252
},
53+
exact: {
54+
type: Boolean,
55+
},
4356
},
4457
setup(props: BetterRouterViewProps, { attrs, slots }) {
4558
const app = getCurrentInstance()!.appContext.app
@@ -76,6 +89,14 @@ export const BetterRouterView: new () => {
7689
return wrappers.get(name)!
7790
}
7891

92+
const route = useRoute()
93+
const viewDepth = inject(viewDepthKey, 0)
94+
provide(
95+
viewDepthKey,
96+
// route.matched 最后一个往往就是精确匹配的,这里更改 viewDepth 后可以让其直接渲染对应的视图组件
97+
computed(() => (props.exact ? route.matched.length - 1 : toValue(viewDepth))),
98+
)
99+
79100
return () =>
80101
h(RouterView, attrs, {
81102
default: (data: Omit<SlotData, 'Component'> & { Component?: VNode }) => {

0 commit comments

Comments
 (0)