Skip to content

VueJS - 路由

Vue 3 - 使用 Vue Router 4 进行客户端路由

Section titled “Vue 3 - 使用 Vue Router 4 进行客户端路由”

单页应用 (SPAs) 需要一种在不同视图或页面之间导航的方式,而无需进行完整的页面重新加载。Vue Router 是处理 Vue 应用路由的官方库。本章介绍如何设置和使用 Vue Router 4(与 Vue 3 兼容的版本)。

Vue Router 需要单独安装。

对于使用 npm 或 yarn 管理的项目(通常通过 Vite 或 Vue CLI 设置):

# NPM
npm install vue-router@4
# Yarn
yarn add vue-router@4

对于简单的项目或直接在 HTML 中进行原型开发:

<!-- Include Vue 3 first -->
<script src="https://unpkg.com/vue@3"></script>
<!-- Then include Vue Router 4 -->
<script src="https://unpkg.com/vue-router@4"></script>

设置 Vue Router 包括定义你的路由、创建一个路由实例,并告诉你的 Vue 应用使用它。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue Router 4 Basic Example</title>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>
<style>
body { font-family: sans-serif; }
nav a { margin: 0 10px; text-decoration: none; color: blue; }
nav a.router-link-active { font-weight: bold; color: darkred; }
.view-content { margin-top: 20px; padding: 15px; border: 1px solid #ccc; background-color: #f9f9f9; }
</style>
</head>
<body>
<div id="app">
<h1>Vue Router Example</h1>
<nav>
<!-- Use router-link for navigation -->
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-link to="/users/1">User 1</router-link>
<router-link to="/users/2">User 2</router-link>
</nav>
<!-- Route outlet: Component matched by the route will render here -->
<router-view></router-view>
</div>
<script>
const { createApp } = Vue;
const { createRouter, createWebHashHistory, createWebHistory } = VueRouter; // 在 CDN 环境中使用 VueRouter 全局对象
// 1. 定义路由组件(在实际应用中可以从文件导入)
const Home = { template: '<div class="view-content"><h2>Home Page</h2><p>Welcome to the home page!</p></div>' };
const About = { template: '<div class="view-content"><h2>About Page</h2><p>Learn more about us here.</p></div>' };
const User = {
// 使用 Composition API 访问路由参数
setup() {
const route = VueRouter.useRoute(); // 访问路由对象
const userId = Vue.computed(() => route.params.id); // 使其成为 computed (计算属性) 以保持响应性
return { userId };
},
template: '<div class="view-content"><h2>User Profile</h2><p>User ID: {{ userId }}</p></div>'
// Options API 等效写法:
// computed: { userId() { return this.$route.params.id } }
};
// 2. 定义路由
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/users/:id', component: User } // 动态路由,带参数 'id'
];
// 3. 创建路由实例
const router = createRouter({
// 使用 hash history 模式进行简单示例 (/#/about)
// 使用 createWebHistory() 实现干净的 URL (需要服务器配置)
history: createWebHashHistory(),
routes, // `routes: routes` 的简写
});
// 4. 创建并挂载 Vue 应用
const app = createApp({});
// 确保 _使用_ 路由实例
app.use(router);
app.mount('#app');
</script>
</body>
</html>
  • 路由组件: 定义与每个视图(Home、About、User)对应的 Vue 组件。在实际应用中,这些通常是单文件组件 (SFCs)。
  • 定义路由: 创建一个数组 (routes),其中每个对象将一个 path 映射到一个 component。:id 这样的动态片段会将 URL 的一部分捕获为参数。
  • 创建路由实例: 使用 createRouter() 配置路由。关键选项包括: * history: 指定历史模式。createWebHashHistory() 使用 URL 哈希(/#/about),无需服务器配置即可工作。createWebHistory() 提供干净的 URL(/about),但需要你的服务器配置回退路由。 * routes: 路由定义数组。
  • 使用路由: 使用 app.use(router) 将路由实例安装到你的 Vue 应用中。这将使路由功能在整个应用中可用。
  • <router-link>: 这个组件会渲染一个 <a> 标签,用于声明式导航。to prop 指定目标路径。
  • <router-view>: 这个组件作为占位符,匹配到的路由组件将在此处渲染。
  • 访问路由参数: 在组件内部,你可以在 Composition API 中使用 VueRouter.useRoute() 或在 Options API 中使用 this.$route 来访问路由信息(例如参数 params)。
  • 活动链接样式: Vue Router 会自动为处于活动状态的 <router-link> 组件添加 CSS 类(router-link-active 和 router-link-exact-active),以便轻松进行样式设置。
  • to (必需): 目标路由。可以是字符串路径 ('/about') 或路由位置对象({ path: '/users/1' },{ name: 'user', params: { id: 1 } } - 需要命名路由)。
  • replace: 如果为 true,导航将调用 router.replace() 而非 router.push(),这意味着它不会向历史堆栈添加新条目(用户无法返回)。
  • active-class: 覆盖默认的 ‘router-link-active’ 类。
  • exact-active-class: 覆盖默认的 ‘router-link-exact-active’ 类。
  • custom: 允许你自定义渲染的元素并通 v-slot API 以编程方式控制导航。示例:<router-link to="/about" custom v-slot="{ navigate, href }"><button :href="href" @click="navigate">Custom Button</button></router-link>

注意:Vue Router 3 中的 tag 和 event props 在 Vue Router 4 中已弃用/移除。请使用带有 v-slot 的 custom prop 来实现类似功能。

除了 <router-link>,你还可以使用路由实例以编程方式进行导航。

// Inside Composition API setup function:
import { useRouter } from 'vue-router';
const router = useRouter();
function goToAbout() {
router.push('/about');
}
function goToUser(userId) {
router.push({ name: 'user', params: { id: userId } }); // Using named route
}
function goBack() {
router.go(-1);
}
// Inside Options API component method:
methods: {
goToAbout() {
this.$router.push('/about');
},
// ... etc
}

在 Composition API 中使用 useRouter() 或在 Options API 中使用 this.$router 来访问路由实例及其方法(push、replace、go)。

Vue Router 提供了更多特性,如命名路由、嵌套路由、导航守卫、懒加载等。请查阅 Vue Router 4 官方文档 了解详细信息。