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