From 494fc5efb6add93c68ed467bb9a8dc7b3b149fff Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Mon, 16 Mar 2020 09:43:37 +0100 Subject: [PATCH] feat(view): allow passing props as a function --- __tests__/RouterView.spec.ts | 24 +++++++++++++++++++++++- src/components/View.ts | 2 +- src/types/index.ts | 5 ++++- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/__tests__/RouterView.spec.ts b/__tests__/RouterView.spec.ts index fdb28b65b..b9397ab8f 100644 --- a/__tests__/RouterView.spec.ts +++ b/__tests__/RouterView.spec.ts @@ -100,11 +100,28 @@ const routes = createRoutes({ matched: [ { components: { default: components.WithProps }, - path: '/users/:id', + path: '/props/:id', props: { id: 'foo', other: 'fixed' }, }, ], }, + + withFnProps: { + fullPath: '/props/1', + name: undefined, + path: '/props/1', + query: { q: 'page' }, + params: { id: '1' }, + hash: '', + meta: {}, + matched: [ + { + components: { default: components.WithProps }, + path: '/props/:id', + props: to => ({ id: Number(to.params.id) * 2, other: to.query.q }), + }, + ], + }, }) describe('RouterView', () => { @@ -194,4 +211,9 @@ describe('RouterView', () => { const { el } = factory(routes.withIdAndOther) expect(el.innerHTML).toBe(`
id:foo;other:fixed
`) }) + + it('can pass a function as props', async () => { + const { el } = factory(routes.withFnProps) + expect(el.innerHTML).toBe(`
id:2;other:page
`) + }) }) diff --git a/src/components/View.ts b/src/components/View.ts index 341e2dc2f..aca948df0 100644 --- a/src/components/View.ts +++ b/src/components/View.ts @@ -41,7 +41,7 @@ export const View = defineComponent({ if (!props) return {} if (props === true) return route.value.params - return props + return typeof props === 'object' ? props : props(route.value) }) provide(matchedRouteKey, matchedRoute) diff --git a/src/types/index.ts b/src/types/index.ts index fd3cd6b15..173118fb1 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -118,7 +118,10 @@ export interface RouteRecordCommon { path: string alias?: string | string[] name?: string - props?: boolean | Record + props?: + | boolean + | Record + | ((to: RouteLocationNormalized) => Record) // TODO: beforeEnter has no effect with redirect, move and test beforeEnter?: NavigationGuard | NavigationGuard[] meta?: Record