Skip to content

Commit f7f8f9f

Browse files
committed
feat(experimental): support type safe route record props
Props are checked against the typed route params and the props of the component of each view, in normalizeRouteRecord() and in definePage(). definePage() props apply to the view of the page.
1 parent f1f6382 commit f7f8f9f

11 files changed

Lines changed: 801 additions & 36 deletions

File tree

‎packages/docs/experimental/router-resolver.md‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,51 @@ definePage({
134134
})
135135
```
136136

137+
## Passing params as props
138+
139+
Use `props` in `definePage()` to pass props to the page component. It applies only to the view of the page component. For example, `props` in `[email protected]` applies to the `sidebar` view:
140+
141+
```vue
142+
<!-- src/pages/users/[userId=int].vue -->
143+
<script setup lang="ts">
144+
defineProps<{ userId: number; page: number }>()
145+
146+
definePage({
147+
params: {
148+
query: { page: { parser: 'int', default: 1 } },
149+
},
150+
// pass route.params (path, query, and hash params) as props
151+
props: true,
152+
})
153+
</script>
154+
```
155+
156+
`props` accepts these values:
157+
158+
- `true`: pass `route.params` as props. This includes the query and hash params.
159+
- `false`: pass no props.
160+
- An object: pass these static props.
161+
- A function: receives the route location and returns the props.
162+
163+
```ts
164+
definePage({
165+
props: to => ({ userId: to.params.userId, page: to.params.page + 1 }),
166+
})
167+
```
168+
169+
With the `sfc-typed-router` Volar plugin, TypeScript checks `props` against the params of the route and against the props of the page component. In the example above, `props: true` gives an error if the component declares a required prop that the params do not supply, or if the types do not match (e.g. `userId: string` with the `int` parser).
170+
171+
Without file-based routing, set `props` on the record, with one entry for each view in `components`. `normalizeRouteRecord()` checks each entry against its component:
172+
173+
```ts
174+
normalizeRouteRecord({
175+
name: 'user',
176+
path: userPath,
177+
components: { default: UserPage, aside: UserAside },
178+
props: { default: true, aside: { compact: true } },
179+
})
180+
```
181+
137182
## With Data Loaders
138183

139184
If you use [Data Loaders](../data-loaders/), install the plugin **before** the router:

‎packages/router/src/experimental/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export { experimental_createRouter, normalizeRouteRecord } from './router'
2+
export type { EXPERIMENTAL_RouteRecordPropsOption } from './route-props'
23
export type {
34
EXPERIMENTAL_Router_Base,
45
EXPERIMENTAL_Router,
@@ -74,6 +75,7 @@ export { miss, MatchMiss as _MatchMiss } from './route-resolver/matchers/errors'
7475
export {
7576
definePage,
7677
_mergeRouteRecord,
78+
_mergeRouteRecordViews,
7779
type DefinePage,
7880
type ParamParserType,
7981
type ParamParserType_Native,
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
/**
2+
* @vitest-environment happy-dom
3+
*/
4+
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
5+
import { defineComponent, h } from 'vue'
6+
import { afterEach, describe, expect, it } from 'vitest'
7+
import {
8+
experimental_createRouter,
9+
normalizeRouteRecord,
10+
type EXPERIMENTAL_RouteRecordNormalized_Matchable,
11+
} from './router'
12+
import { createFixedResolver } from './route-resolver/resolver-fixed'
13+
import {
14+
MatcherPatternPathDynamic,
15+
MatcherPatternPathStatic,
16+
} from './route-resolver/matchers/matcher-pattern'
17+
import { MatcherPatternQueryParam } from './route-resolver/matchers/matcher-pattern-query'
18+
import { PARAM_PARSER_INT } from './route-resolver/matchers/param-parsers'
19+
import { _mergeRouteRecordViews } from './runtime'
20+
import { createMemoryHistory } from '../history/memory'
21+
import { RouterView } from '../RouterView'
22+
23+
enableAutoUnmount(afterEach)
24+
25+
const User = defineComponent({
26+
props: {
27+
id: { type: Number, required: true },
28+
page: { type: Number, default: 0 },
29+
label: String,
30+
},
31+
setup: props => () =>
32+
h(
33+
'p',
34+
`${typeof props.id}:${props.id} page:${props.page} label:${props.label}`
35+
),
36+
})
37+
38+
const Aside = defineComponent({
39+
props: { title: String },
40+
setup: props => () => h('aside', `title:${props.title}`),
41+
})
42+
43+
const userPath = new MatcherPatternPathDynamic(
44+
/^\/users\/([^/]+?)$/i,
45+
{ id: [PARAM_PARSER_INT] },
46+
['users', 1]
47+
)
48+
const pageQuery = [
49+
new MatcherPatternQueryParam('page', 'page', 'value', PARAM_PARSER_INT, 1),
50+
]
51+
52+
async function mountRouter(
53+
...records: EXPERIMENTAL_RouteRecordNormalized_Matchable[]
54+
) {
55+
const router = experimental_createRouter({
56+
history: createMemoryHistory(),
57+
resolver: createFixedResolver([
58+
...records,
59+
normalizeRouteRecord({
60+
name: 'start',
61+
path: new MatcherPatternPathStatic('/'),
62+
components: {},
63+
}),
64+
]),
65+
})
66+
await router.push('/')
67+
const wrapper = mount(
68+
defineComponent({
69+
components: { RouterView },
70+
template: `<RouterView /><RouterView name="aside" />`,
71+
}),
72+
{ global: { plugins: [router] } }
73+
)
74+
return { router, wrapper }
75+
}
76+
77+
describe('Experimental route record props', () => {
78+
it('passes parsed params as props with `true`', async () => {
79+
const { router, wrapper } = await mountRouter(
80+
normalizeRouteRecord({
81+
name: 'user',
82+
path: userPath,
83+
query: pageQuery,
84+
components: { default: User },
85+
props: { default: true },
86+
})
87+
)
88+
await router.push('/users/42?page=3')
89+
await flushPromises()
90+
expect(wrapper.text()).toBe('number:42 page:3 label:undefined')
91+
})
92+
93+
it('passes the result of a function', async () => {
94+
const { router, wrapper } = await mountRouter(
95+
normalizeRouteRecord({
96+
name: 'user',
97+
path: userPath,
98+
components: { default: User },
99+
props: {
100+
default: to => ({ id: Number(to.params.id) * 2, label: 'fn' }),
101+
},
102+
})
103+
)
104+
await router.push('/users/7')
105+
await flushPromises()
106+
expect(wrapper.text()).toBe('number:14 page:0 label:fn')
107+
})
108+
109+
it('passes props to each named view', async () => {
110+
const { router, wrapper } = await mountRouter(
111+
normalizeRouteRecord({
112+
name: 'user',
113+
path: userPath,
114+
components: { default: User, aside: Aside },
115+
props: { default: true, aside: { title: 'static' } },
116+
})
117+
)
118+
await router.push('/users/1')
119+
await flushPromises()
120+
expect(wrapper.find('p').text()).toBe('number:1 page:0 label:undefined')
121+
expect(wrapper.find('aside').text()).toBe('title:static')
122+
})
123+
124+
it('passes no params to views without props', async () => {
125+
const { router, wrapper } = await mountRouter(
126+
normalizeRouteRecord({
127+
name: 'user',
128+
path: userPath,
129+
components: { default: User, aside: Aside },
130+
props: { default: true },
131+
})
132+
)
133+
await router.push('/users/1')
134+
await flushPromises()
135+
expect(wrapper.find('aside').text()).toBe('title:undefined')
136+
})
137+
138+
it('passes definePage() props to the view of the page', async () => {
139+
const { router, wrapper } = await mountRouter(
140+
normalizeRouteRecord(
141+
_mergeRouteRecordViews(
142+
{
143+
name: 'user',
144+
path: userPath,
145+
components: { default: User, aside: Aside },
146+
},
147+
{
148+
default: { props: true },
149+
aside: { props: to => ({ title: `user ${to.params.id}` }) },
150+
}
151+
)
152+
)
153+
)
154+
await router.push('/users/5')
155+
await flushPromises()
156+
expect(wrapper.find('p').text()).toBe('number:5 page:0 label:undefined')
157+
expect(wrapper.find('aside').text()).toBe('title:user 5')
158+
})
159+
})
160+
161+
describe('_mergeRouteRecordViews', () => {
162+
it('sets the props of each page on its view', () => {
163+
const record = _mergeRouteRecordViews(
164+
{ meta: {}, props: {} },
165+
{
166+
default: { props: true },
167+
aside: { props: { title: 'a' } },
168+
}
169+
)
170+
expect(record.props).toEqual({ default: true, aside: { title: 'a' } })
171+
})
172+
173+
it('merges meta of all the pages', () => {
174+
const record = _mergeRouteRecordViews(
175+
{ meta: { a: 1 } },
176+
{
177+
default: { meta: { b: 2 } },
178+
aside: { meta: { c: 3 } },
179+
}
180+
)
181+
expect(record.meta).toEqual({ a: 1, b: 2, c: 3 })
182+
})
183+
184+
it('keeps the properties extracted at build time', () => {
185+
const path = new MatcherPatternPathStatic('/about')
186+
const record = _mergeRouteRecordViews(
187+
{ name: '/about', path },
188+
{
189+
default: {
190+
name: 'custom',
191+
path: '/custom',
192+
alias: ['/other'],
193+
params: { query: { page: 'int' } },
194+
},
195+
}
196+
)
197+
expect(record).toEqual({ name: '/about', path })
198+
})
199+
200+
it('keeps other properties of the page', () => {
201+
const redirect = () => '/'
202+
const record = _mergeRouteRecordViews({}, { default: { redirect } })
203+
expect(record).toEqual({ redirect })
204+
})
205+
})
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import type {
2+
RouteLocationNormalizedLoaded,
3+
RouteLocationNormalizedLoadedGeneric,
4+
RouteMap,
5+
} from '../typed-routes'
6+
7+
/**
8+
* Props declared by a route component. Lazy components are unwrapped. When
9+
* the component type is unknown, any props are accepted.
10+
*
11+
* @internal
12+
*/
13+
export type _ComponentProps<C> = unknown extends C
14+
? Record<string, any>
15+
: C extends () => Promise<infer M>
16+
? _ComponentProps<M extends { default: infer D } ? D : M>
17+
: C extends new (...args: any) => { $props: infer P }
18+
? P
19+
: C extends (props: infer P, ...args: any) => any
20+
? P
21+
: Record<string, any>
22+
23+
/**
24+
* `true` is only allowed if the route params can be passed as props. Generic
25+
* params (no typed routes) have an index signature and cannot be checked.
26+
*
27+
* @internal
28+
*/
29+
export type _RoutePropsTrue<Params, Props> = string extends keyof Params
30+
? true
31+
: [Params] extends [Props]
32+
? true
33+
: never
34+
35+
/**
36+
* Value of the `props` option for one view of a route record.
37+
*
38+
* - `true`: pass `route.params` as props. The params must match the props of
39+
* the component.
40+
* - `false`: pass no props.
41+
* - object: pass these static props.
42+
* - function: receives the route location and returns the props.
43+
*
44+
* @typeParam Location - route location that renders the view
45+
* @typeParam Props - props of the component of the view
46+
*/
47+
export type EXPERIMENTAL_RouteRecordPropsOption<
48+
Location extends RouteLocationNormalizedLoadedGeneric =
49+
RouteLocationNormalizedLoadedGeneric,
50+
Props = Record<string, any>,
51+
> =
52+
| false
53+
| _RoutePropsTrue<Location['params'], Props>
54+
| Props
55+
| ((to: Location) => Props)
56+
57+
/**
58+
* Route location that can render a record named `Name`: the record itself
59+
* and all its children.
60+
*
61+
* @internal
62+
*/
63+
export type _RouteLocationForRecordName<Name> = Name extends keyof RouteMap
64+
? RouteLocationNormalizedLoaded<Name | RouteMap[Name]['childrenNames']>
65+
: RouteLocationNormalizedLoadedGeneric
66+
67+
/**
68+
* `props` option of a route record, one entry per view in `components`.
69+
*
70+
* @internal
71+
*/
72+
export type _RouteRecordPropsViews<
73+
Location extends RouteLocationNormalizedLoadedGeneric,
74+
Components,
75+
> = {
76+
[View in keyof Components]?: EXPERIMENTAL_RouteRecordPropsOption<
77+
Location,
78+
_ComponentProps<Components[View]>
79+
>
80+
}

0 commit comments

Comments
 (0)