Skip to content

路由

客户端路由 vs. 服务端路由

服务端路由意味着服务器会根据用户正在访问的 URL 路径返回响应。在传统的服务端渲染 Web 应用中,当我们点击一个链接时,浏览器会从服务器接收 HTML 响应,并使用新的 HTML 重新加载整个页面。

然而,在 单页应用(SPA)中,客户端 JavaScript 可以拦截导航,动态获取新数据,并在不进行整页刷新 的情况下更新当前页面。这通常会带来更流畅的用户体验,尤其适用于更像真正“应用程序”的场景,即用户需要在较长时间内进行大量交互。

在这类 SPA 中,“路由”是在客户端、也就是浏览器中完成的。客户端路由器负责使用浏览器 API(例如 History APIhashchange 事件)来管理应用程序渲染出的视图。

官方路由器

Vue 非常适合构建 SPA。对于大多数 SPA,建议使用官方支持的 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="#/">首页</a> |
  <a href="#/about">关于</a> |
  <a href="#/non-existent-path">失效链接</a>
  <component :is="currentView" />
</template>

在 Playground 中试试

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="#/">首页</a> |
  <a href="#/about">关于</a> |
  <a href="#/non-existent-path">失效链接</a>
  <component :is="currentView" />
</template>

在 Playground 中试试

路由 has loaded