<NuxtPage>
<NuxtPage> - это встроенный компонент, который идет вместе с Nuxt. Он позволяет отображать страницы верхнего уровня или вложенные страницы, расположенные в директории pages/.
<NuxtPage> is a wrapper around <RouterView> from Vue Router. It should be used instead of <RouterView> because the former takes additional care of internal states. Otherwise, useRoute() may return incorrect paths.<NuxtPage> includes the following components:
<template>
<RouterView #default="{ Component }">
<!-- Optional, when using transitions -->
<Transition>
<!-- Optional, when using keep-alive -->
<KeepAlive>
<Suspense>
<component :is="Component" />
</Suspense>
</KeepAlive>
</Transition>
</RouterView>
</template>
By default, Nuxt does not enable <Transition> and <KeepAlive>. You can enable them in the nuxt.config file or by setting the transition and keepalive properties on <NuxtPage>. If you want to define a specific page, you can set it in definePageMeta in the page component.
<Transition> in your page component, ensure that the page has a single root element.Since <NuxtPage> uses <Suspense> under the hood, the component lifecycle behavior during page changes differs from that of a typical Vue application.
In a typical Vue application, a new page component is mounted only after the previous one has been fully unmounted. However, in Nuxt, due to how Vue <Suspense> is implemented, the new page component is mounted before the previous one is unmounted.
Входные параметры
name: указывает<RouterView>отобразить компонент с соответствующим именем в опции components записи соответствующего маршрута.- тип:
string
- тип:
route: местоположение маршрута, в котором есть все его компоненты.- тип:
RouteLocationNormalized
- тип:
pageKey: контролирует, когда будет произведен повторный рендер компонентаNuxtPage.- тип:
stringилиfunction
- тип:
transition: определяет глобальные переходы для всех страниц, отрендеренных с помощьюNuxtPage.- тип:
booleanилиTransitionProps
- тип:
keepalive: контролирует сохранение состояния страниц, отрендеренных с помощьюNuxtPage.- тип:
booleanилиKeepAliveProps
- тип:
name и route, сканируя и отображая все файлы компонентов Vue, найденные в директории /pages.Пример
For example, if you pass a key that never changes, the <NuxtPage> component will be rendered only once - when it is first mounted.
<template>
<NuxtPage page-key="static" />
</template>
Вы также можете использовать динамический ключ, основывающийся на текущем маршруте:
<NuxtPage :page-key="route => route.fullPath" />
$route, так как это может вызвать проблемы с тем, как <NuxtPage> рендерит страницы с <Suspense>.В качестве альтернативы можно передать pageKey в качестве значения key через definePageMeta из тега <script> компонента Vue в директории
/pages.
<script setup lang="ts">
definePageMeta({
key: route => route.fullPath
})
</script>
Ссылка на страницу
Чтобы получить ref компонента страницы, обратитесь к нему через ref.value.pageRef
<script setup lang="ts">
const page = ref()
function logFoo () {
page.value.pageRef.foo()
}
</script>
<template>
<NuxtPage ref="page" />
</template>
<script setup lang="ts">
const foo = () => {
console.log('вызван метод foo')
}
defineExpose({
foo,
})
</script>
Пользовательские входные параметры
<NuxtPage> также принимает пользовательские входные параметры, которые вам, возможно, потребуется передать ниже по иерархии.
For example, in the below example, the value of foobar will be passed to the NuxtPage component and then to the page components.
<template>
<NuxtPage :foobar="123" />
</template>
We can access the foobar prop in the page component:
<script setup lang="ts">
const props = defineProps<{ foobar: number }>()
console.log(props.foobar) // Outputs: 123
If you have not defined the prop with defineProps, any props passed down to NuxtPage can still be accessed directly from the page attrs:
<script setup lang="ts">
const attrs = useAttrs()
console.log(attrs.foobar) // Outputs: 123
</script>