跳轉到內容

路由

客戶端路由與伺服器端路由

在伺服器端進行路由意味著伺服器根據使用者訪問的 URL 路徑傳送響應。當我們在一個傳統的伺服器端渲染的 Web 應用中點選連結時,瀏覽器從伺服器接收 HTML 響應,並使用新的 HTML 重新載入整個頁面。

然而,在單頁應用程式 (SPA) 中,客戶端 JavaScript 可以攔截導航,動態獲取新資料,並在不進行完整頁面重新載入的情況下更新當前頁面。這通常會導致更流暢的使用者體驗,尤其是對於更類似於實際“應用程式”的使用場景,使用者需要在長時間內執行許多互動。

在這種 SPAs 中,路由是在客戶端,在瀏覽器中進行的。客戶端路由器負責使用瀏覽器 API(如 History APIhashchange 事件)管理應用程式的渲染檢視。

官方路由器

Vue 非常適合構建單頁應用程式。對於大多數單頁應用程式,建議使用官方支援的 Vue Router 庫。更多詳情請參閱 Vue Router 的 文件

從頭開始簡單路由

如果您只需要非常簡單的路由並且不想涉及功能齊全的路由庫,您可以使用 動態元件,並透過監聽瀏覽器 hashchange 事件 或使用 History API 來更新當前元件狀態。

以下是一個簡單的示例

vue
<script setup>
import { ref, computed } from 'vue'
import Home from './Home.vue'
import About from './About.vue'
import NotFound from './NotFound.vue'

const routes = {
  '/': Home,
  '/about': About
}

const currentPath = ref(window.location.hash)

window.addEventListener('hashchange', () => {
  currentPath.value = window.location.hash
})

const currentView = computed(() => {
  return routes[currentPath.value.slice(1) || '/'] || NotFound
})
</script>

<template>
  <a href="#/">Home</a> |
  <a href="#/about">About</a> |
  <a href="#/non-existent-path">Broken Link</a>
  <component :is="currentView" />
</template>

在沙盒中嘗試

vue
<script>
import Home from './Home.vue'
import About from './About.vue'
import NotFound from './NotFound.vue'

const routes = {
  '/': Home,
  '/about': About
}

export default {
  data() {
    return {
      currentPath: window.location.hash
    }
  },
  computed: {
    currentView() {
      return routes[this.currentPath.slice(1) || '/'] || NotFound
    }
  },
  mounted() {
    window.addEventListener('hashchange', () => {
		  this.currentPath = window.location.hash
		})
  }
}
</script>

<template>
  <a href="#/">Home</a> |
  <a href="#/about">About</a> |
  <a href="#/non-existent-path">Broken Link</a>
  <component :is="currentView" />
</template>

在沙盒中嘗試

路由已載入