為什麼我們會需要 Vue Router,或放大來說:
為甚麼我們需要路由管理呢?
現代大多的前端框架都是採 SPA 架構,
這也代表了頁面切換是不再依靠瀏覽器重新載入的,
而是由前端主動維護不同頁面的 視圖 狀態。
可以透過網址 ( URL ) 來管理不同頁面,搭配 SSR 能提升 SEO,
省去許多處理跳轉頁面的功夫,還可以根據權限阻擋,
動態路由等等…,好處可以說是非常多啊。
視圖 : MVC 或 MVVM 架構中的 View,主要指視覺畫面 ( 使用者看到的樣子
SEO : 搜尋引擎優化,主要目的是讓搜尋關鍵字時你的網站可以排名更靠前。
跟著接下來的步驟開始練習吧,或是可以透過這個 遊樂場 先小試身手。
如果你還沒有安裝 vue-router
可以在專案中的 terminal
輸入這行 :
$ npm install vue-router@4
// src/routes/index.js
import { createWebHistory, createRouter } from "vue-router";
import HomeView from "../views/HomeView.vue";
import AboutView from "../views/AboutView.vue";
const routes = [
{ path: "/", component: HomeView },
{ path: "/about", component: AboutView },
];
const router = createRouter({
history: createWebHistory(), /* 這邊要注意,不是用 createMemoryHistory() */
routes,
});
export default router;
createMemoryHistory
完全忽略瀏覽器的 URL 而是使用其自己內部的 URL,
因此如果你用了發現畫面有變但是 URL 沒變,
請使用createWebHistory
或是createWebHashHistory()
到你的 main.js
全域註冊它
import { createApp } from 'vue'
import router from '@/router' // 引入剛剛建立的 router
import App from '@/App.vue'
createApp(App)
.use(router) // 並在這邊註冊它
.mount('#app')
註冊 :
這邊的註冊並不是平常我們說的登入註冊那種,
而是讓 Vue 知道這個元件會在哪裡被使用,分為全域和局部。
這時候你可能會看到錯誤 :
不用太擔心,因為我們還沒有創建頁面。
<!-- App.vue -->
<template>
<h1>早上好! 鐵人賽</h1>
<p>
<strong>現在的路由是</strong> {{ $route.fullPath }}
<!-- $ 代表全域 -->
</p>
<main>
<RouterView />
<!-- 這根據 URL 來決定要塞什麼資料到這個 RouterView -->
</main>
</template>
<!-- src/views/HomeView.vue -->
<script setup>
import { useRouter } from "vue-router";
const router = useRouter();
function goToAbout() {
router.push("/about");
}
</script>
<template>
<h2>HomeView</h2>
<button @click="goToAbout">去 About</button>
</template>
<!-- src/views/AboutView.vue -->
<script setup>
import { useRouter } from "vue-router";
const router = useRouter();
function goToHome() {
router.push("/");
}
</script>
<template>
<h2>AboutView</h2>
<button @click="goToHome">去 Home</button>
</template>
這樣就是一個快速簡單切換的頁面,也可以直接輸入 URL 來切換畫面
在我個人的經驗看來,怎麼學好一個套件就是先用,
然後你總會遇到一些問題,根據這些問題去查找文件或是討論,
這個學習效率會比你全部都讀完再開始寫會好得很多,
因此這個篇章都會採這個架構。
對於一個套件完全陌生的人來講,
先看到實際的結果再去探討原因有一個好處,
就是你可以透過實際畫面去了解抽象概念,
等你知道的概念夠多後,學其它類似或新的套件都能舉一反三。
那今天呢我們帶過了 vue-router 的基本使用方法,明天將會進入進階使用環節。
如果你喜歡這個系列或是想看我發瘋,歡迎按下 訂閱
一起走完這三十天吧。