iT邦幫忙

2025 iThome 鐵人賽

DAY 30
0
Vue.js

Vue.js 新手入門之路系列 第 30

Vue.js 新手入門之路 - router(三)

  • 分享至 

  • xImage
  •  

擷取找不到的路由

我們可以自訂一個畫面讓未知、找不到的路由都導向這邊
eg.
建立 views/NotFound.vue

<template>
  <section style="padding:24px">
    <h2>404 - Not Found</h2>
    <p>找不到頁面:<code>{{ $route.fullPath }}</code></p>
    <RouterLink to="/">回首頁</RouterLink>
  </section>
</template>

router/index.js 再加入一行 NotFound 路由

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
import User from '../views/User.vue'
import NotFound from '../views/NotFound.vue'

export default createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', name: 'home', component: Home },
    { path: '/about',name: 'about', component: About },
    { path: '/users/:id', name: 'user', component: User }, // 動態參數
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
  ],
})

components/Go404.vue

<script setup>
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

function go404() {
  router.push({
    name: 'NotFound',
    params: { pathMatch: route.path.substring(1).split('/') },
    query: route.query,
    hash: route.hash,
  })
}
</script>

<template>
  <button @click="go404">go 404</button>
</template>

App.vue

<script setup>
import Go404 from './components/Go404.vue'
</script>

<template>
  <h1>Hello App!</h1>
  <p><strong>Current route path:</strong> {{ $route.fullPath }}</p>
  <nav>
    <RouterLink to="/">Go to Home</RouterLink>
    <RouterLink to="/about">Go to About</RouterLink>
    <RouterLink to="/users/johnny">johnny</RouterLink>
    <RouterLink to="/users/jolyne">jolyne</RouterLink>
  </nav>
  <br>
  <Go404/>
  <main><RouterView /></main>
</template>

<style scoped>
  nav{
    display: flex;
    flex-direction: column;
    gap: 3px;
  }
</style>

可以故意打一些未定義的路由試試看,它們都會進到 NotFound.vue
https://ithelp.ithome.com.tw/upload/images/20250919/20178296HYXLE7O1u9.pnghttps://ithelp.ithome.com.tw/upload/images/20250919/20178296hWS5qhXZuL.png

ref:
https://router.vuejs.org/zh/guide/essentials/dynamic-matching.html


上一篇
Vue.js 新手入門之路 - router(二)
系列文
Vue.js 新手入門之路30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
Yanya
iT邦新手 5 級 ‧ 2025-09-19 14:04:33

恭喜完賽!

normie_a iT邦新手 5 級 ‧ 2025-09-19 14:10:23 檢舉

雖然我覺得我有好多篇都寫的不好,但還是感謝你

我要留言

立即登入留言