在应用程序的生命周期中,一些错误可能会在运行时意外出现。在这种情况下,我们可以使用 error.vue 文件来覆盖默认的错误文件并优雅地显示错误。
<script setup lang="ts">
import type { NuxtError } from '#app'
const props = defineProps({
error: Object as () => NuxtError,
})
</script>
<template>
<div>
<h1>{{ error.statusCode }}</h1>
<NuxtLink to="/">Go back home</NuxtLink>
</div>
</template>
~/pages 目录中。出于同样的原因,您不应在此页面中使用 definePageMeta。话虽如此,您仍然可以通过使用 NuxtLayout 组件并指定布局名称来在错误文件中使用布局。错误页面有一个单独的 prop - error,其中包含一个供您处理的错误。
error 对象提供以下字段
interface NuxtError {
statusCode: number
fatal: boolean
unhandled: boolean
statusMessage?: string
data?: unknown
cause?: unknown
}
如果您的错误包含自定义字段,它们将丢失;您应该将其分配给 data
throw createError({
statusCode: 404,
statusMessage: 'Page Not Found',
data: {
myCustomField: true,
},
})