0
0

More than 1 year has passed since last update.

【Rails × Vue】ルーティングエラー404の際に専用のコンポーネントを表示する

Posted at

実現したいこと

routes.rbで設定したパス以外のURLにアクセスがあった際(エラーステータス404)にVueで’ページが見つかりません’のようなメッセージを表示するコンポーネントを描出する。

Rails側の設定

routes.rb
Rails.application.routes.draw do

.
.
.
match '*path', :to => 'application#error404', :via => :all
#設定外のパスにアクセスがあった際にapplication_controllerの[error404]というアクションを実行する。

end

application_controller.rb

class ApplicationController < ActionController::Base

  rescue_from Exception, with: :error404
  rescue_from ActiveRecord::RecordNotFound,
  ActionController::RoutingError, with: :error404

  def error404(e)
    render "error404", status: 404 
  end

end


Vue側の設定

Error.vue

<template>
 <h1>指定のページが見つかりません。</h1>
</template>

<script>
export default {
  name: 'Error'
}
</script>

router.js

import Error from './任意のディレクトリ/Error.vue'

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/404NotFound',
      name: 'Error',
      component: Error
    }

App.vue

<template>
  <main>
    <Header> //今回はHeader componentでエラー404をキャッチするメソッドを実装する
    <div>
      <router-view />
    </div>
    <Footer/>
  </main>
</template>

Header.vue
<template>
省略
</template>

<script>

 export default {
 name: 'Header',
 mounted() {
  this.notFoundPage();
 },
 methods: {
  notFoundPage: function() {
        axios.get(location.pathname) //location.pathnameは現在滞在しているURLを表す。
        .catch(error => {
          if(error.response.status === 404) {
            this.$router.push({name: 'Error'})
          }
        })
      }
    }
  }

</script>
0
0
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
0
0