跳到主要内容

error.vue

error.vue 文件是你 Nuxt 应用中的错误页面。

在应用的生命周期中,运行时可能会意外出现一些错误。在这种情况下,我们可以使用 error.vue 文件来覆盖默认的错误文件,并优雅地展示错误。

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="/">返回首页</NuxtLink>
  </div>
</template>
虽然它被称为「错误页面」,但它不是路由,不应放在你的 ~/pages 目录中。出于同样的原因,你不应在此页面中使用 definePageMeta。也就是说,你仍然可以在错误文件中使用布局,方法是使用 NuxtLayout 组件并指定布局名称。

错误页面有一个单独的 prop——error,它包含一个供你处理的错误。

error 对象提供以下字段:

interface NuxtError {
  status: number
  fatal: boolean
  unhandled: boolean
  statusText?: string
  data?: unknown
  cause?: unknown
}

如果你有带自定义字段的错误,这些字段会丢失;你应该将它们赋给 data

throw createError({
  status: 404,
  statusText: 'Page Not Found',
  data: {
    myCustomField: true,
  },
})