0
0

More than 1 year has passed since last update.

【Vue.Router】404ページへの遷移

Posted at

404ページへの遷移

urlに存在しないページへのpathをリクエストした場合の404ページの表示方法

環境

@vue/cli 4.5.12

手順

ルーテイングを管理するrouter/index.jsで以下のように設定。

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
//NotFoundコンポーネントをimport
import NotFound from '@/someDir/NotFound.vue'

Vue.use(VueRouter)

const routes = [

  {
    path: '*', //設定したurlにいずれもマッチしない場合
    // redirect: '/', ※redirectオプションは任意で設定
    component: NotFound //NotFoundコンポーネントに遷移

  }
]

const router = new VueRouter({ //routerインスタンスを作成
  mode: 'history',
  base: process.env.BASE_URL,
  routes 
})

export default router

  • NotFound.vue
    • 表示させる内容は任意
someDir/NotFound.vue

<template>
  <div>
      <h1>404 ページが存在しません。</h1>
      <button @click="goHome">ホームに戻る</button>
  </div>
</template>

<script>
export default {
    methods:{
        goHome(){
            this.$router.push('/') //ボタンを押した時の遷移先
        }
    }
}
</script>


<style>

</style>
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