feat(nuxt): support redirect within page metadata (#7746)

This commit is contained in:
Daniel Roe 2022-09-22 14:54:34 +01:00 committed by GitHub
parent aec2e02bd3
commit 1c26e07141
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 41 additions and 2 deletions

View File

@ -1,8 +1,20 @@
import { KeepAliveProps, TransitionProps, UnwrapRef } from 'vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import type { RouteLocationNormalizedLoaded, RouteRecordRedirectOption } from 'vue-router'
export interface PageMeta {
[key: string]: any
/**
* Where to redirect if the route is directly matched. The redirection happens
* before any navigation guard and triggers a new navigation with the new
* target location.
*/
redirect?: RouteRecordRedirectOption
/**
* Aliases for the record. Allows defining extra paths that will behave like a
* copy of the record. Allows having paths shorthands like `/users/:id` and
* `/u/:id`. All `alias` and `path` values must share the same params.
*/
alias?: string | string[]
pageTransition?: boolean | TransitionProps
layoutTransition?: boolean | TransitionProps
key?: false | string | ((route: RouteLocationNormalizedLoaded) => string)

View File

@ -243,6 +243,7 @@ export function normalizeRoutes (routes: NuxtPage[], metaImports: Set<string> =
children: route.children ? normalizeRoutes(route.children, metaImports).routes : [],
meta: route.meta ? `{...(${metaImportName} || {}), ...${JSON.stringify(route.meta)}}` : metaImportName,
alias: aliasCode,
redirect: route.redirect ? JSON.stringify(route.redirect) : `${metaImportName}?.redirect || undefined`,
component: genDynamicImport(file, { interopDefault: true })
}
}))

View File

@ -43,7 +43,8 @@ export type NuxtPage = {
path: string
file: string
meta?: Record<string, any>
alias?: string[]
alias?: string[] | string
redirect?: string
children?: NuxtPage[]
}

View File

@ -55,6 +55,16 @@ describe('pages', () => {
await expectNoClientErrors('/')
})
it('respects aliases in page metadata', async () => {
const html = await $fetch('/some-alias')
expect(html).toContain('Hello Nuxt 3!')
})
it('respects redirects in page metadata', async () => {
const { headers } = await fetch('/redirect', { redirect: 'manual' })
expect(headers.get('location')).toEqual('/')
})
it('render 404', async () => {
const html = await $fetch('/not-found')

View File

@ -28,6 +28,10 @@ setupDevtoolsPlugin({}, () => {})
const config = useRuntimeConfig()
definePageMeta({
alias: '/some-alias'
})
// reset title template example
useHead({
titleTemplate: ''

11
test/fixtures/basic/pages/redirect.vue vendored Normal file
View File

@ -0,0 +1,11 @@
<script setup>
definePageMeta({
redirect: () => '/'
})
</script>
<template>
<div>
<div>redirect.vue</div>
</div>
</template>