ianhuang筆記THE ADVENTURER'S JOURNAL
知識世界・持續探索中

ADVENTURE JOURNAL · 探索筆記

Vue 教學 16:匹配、重新導向與找不到頁面

任務導覽 TABLE OF CONTENTS

在共用骨架加入任務頁、重新導向與 404,檢查路由匹配的完整行為。

適用:Vue 3.5 與 Vue Router 4。先完成第 00 章環境與 第 15 章的路由骨架 ,後續範例依指定檔案替換。

擴充 routes

建立 src/views/NotFound.vue:

<template><h1>找不到這個任務</h1><RouterLink to="/">回首頁</RouterLink></template>

在第 15 章 router.js 匯入 NotFound,將 routes 改為:

const routes = [
  { path: '/', name: 'home', component: Home },
  { path: '/about', name: 'about', component: About },
  { path: '/start', redirect: { name: 'home' } },
  { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFound }
]

將 createRouter 裡的 routes: [...] 改為 routes。開啟 #/start 應轉到首頁;開 #/missing 應顯示找不到任務。catch-all 是 Router 4 寫法,不能使用 Router 3 的單獨 * 路徑。

active class 與導向

RouterLink 會為符合紀錄的連結加入 active class,巢狀頁面可能使父連結也 active;只要完全相符用 exact-active-class。redirect 改變目的地,alias 則讓不同網址對應同一紀錄且保留使用者輸入的網址。

SPA 顯示 404 元件不代表伺服器回應 HTTP 404,SEO 或 SSR 需要後端配合。這份入門骨架使用 hash,只展示前端狀態;部署回應碼另行驗證。

章節導覽

系列目錄 · 上一章 · 下一章

參考資料

冒險者留言

comments powered by Disqus

搜尋筆記

輸入關鍵字,探索所有筆記。

ESC 關閉 · 搜尋標題、標籤與文章全文