LoginSignup
34
22

More than 5 years have passed since last update.

Nuxt.jsで存在しないURLにアクセスされた時に404ページ(任意のページ)を表示する方法

Last updated at Posted at 2019-03-13

解決したいこと

Nuxt.jsで存在しないURLでアクセスされた時に任意の404ページを出力させたい。

解決方法

nuxt.config.jsに以下のようにルーティングルールを設定することで解決することができます。

nuxt.config.js
  // Routing configuration
  router: {
    extendRoutes (routes, resolve) {
      routes.push({
        name: 'custom',
        path: '*',
        component: resolve(__dirname, 'pages/errors/404.vue')
      })
    }
  }

あとはcomponentで指定したページを用意するだけです。

pages/errors/404.vue
<template>
  <p>出力される404ページ</p>
</template>

404以外のエラーも一括で対応したい時

エラー系のページは全部同じレイアウトでええ!って時はlayouts/error.vueが便利です。
エラーが起きた時はlayouts/error.vueが表示されます。ファイルを置くだけなので簡単です。
エラーコードによる文言の出し分けも、もちろんできます。

layouts/error.vue
<template>
  <div class="container">
    <h1>{{ error.statusCode }}</h1>
    <p v-if="error.statusCode === 404">
      ページが見つかりません
    </p>
    <p v-else>
      エラーが発生しました
    </p>
  </div>
</template>

<script>
export default {
  props: {
    error: {
      type: Object,
      default: null
    }
  }
}
</script>

まとめ

今回は存在しないURLにアクセスされた時に任意のページを表示する方法を紹介しました。
普通はlayouts/error.vueを置く方法で404系は対応できますが、
404を凝ったページを表示したい時や、出し分けせずに別ページで対応したい場合などの用途にお使いください。

34
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
22