Vue Router 是 Vue.js 官方的单页面应用(SPA)路由管理器,其核心原理如下:
-
路由模式:
- Hash 模式:通过 URL 的
#部分(如http://site.com/#/home)实现无刷新跳转,监听hashchange事件。 - History 模式:利用 HTML5 History API(
pushState/replaceState)操作 URL(如http://site.com/home),需服务器支持。
- Hash 模式:通过 URL 的
-
组件映射:
- 将 URL 路径映射到对应的 Vue 组件。
- 路径变化时,动态渲染匹配的组件到
<router-view>位置。
-
导航守卫:
- 通过全局/路由级的钩子函数(如
beforeEach)控制导航流程。
- 通过全局/路由级的钩子函数(如
基本使用步骤及作用
1. 安装 Vue Router
npm install vue-router@4
- 作用:安装适用于 Vue 3 的 Vue Router 4 版本。
2. 创建路由实例
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes = [
{
path: '/', // URL 路径
name: 'Home', // 路由名称(可选)
component: Home // 映射的组件
},
{
path: '/about/:id?', // 动态路由(:id 为参数,? 表示可选)
name: 'About',
component: About,
props: true, // 将路由参数作为 props 传递
meta: { requiresAuth: true } // 路由元信息
}
];
const router = createRouter({
history: createWebHistory(), // 使用 History 模式
routes // 注册路由配置
});
export default router;
- 作用:
routes:定义路径与组件的映射关系。history:选择路由模式(createWebHashHistory()为 Hash 模式)。props: true:将路由参数自动传入组件 props。meta:存储路由元信息(如页面权限)。
3. 挂载路由到 Vue 应用
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router); // 启用路由系统
app.mount('#app');
- 作用:将路由实例注入整个应用,使所有组件能访问
$router和$route。
4. 在组件中使用路由
<!-- App.vue -->
<template>
<div>
<!-- 导航链接 -->
<router-link to="/">Home</router-link>
<router-link :to="{ name: 'About', params: { id: 1 } }">About</router-link>
<!-- 路由出口:匹配的组件在此渲染 -->
<router-view></router-view>
</div>
</template>
- 作用:
<router-link>:生成无刷新导航链接(默认渲染为<a>标签)。<router-view>:路由匹配的组件渲染位置。
5. 编程式导航
// 在组件中通过 Composition API 使用
import { useRouter, useRoute } from 'vue-router';
export default {
setup() {
const router = useRouter();
const route = useRoute(); // 当前路由信息
// 跳转到 About 页
const goToAbout = () => {
router.push({ name: 'About', params: { id: 123 } }); // 等价于 router.push('/about/123')
};
// 获取路由参数
console.log(route.params.id); // 输出动态路由参数
return { goToAbout };
}
};
- 作用:
router.push():导航到新路由(添加历史记录)。router.replace():替换当前路由(无历史记录)。router.go():在历史记录中前进/后退。useRoute():访问当前路由信息(参数、查询字符串等)。
6. 导航守卫
// 全局前置守卫(在 router/index.js 中)
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login'); // 重定向到登录页
} else {
next(); // 允许导航
}
});
- 作用:
beforeEach:全局路由跳转前触发(常用作权限验证)。- 其他守卫:
beforeResolve、afterEach、路由独享守卫beforeEnter。 - 组件内守卫:
beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave。
关键概念总结
| 功能 | API/组件 | 作用 |
|---|---|---|
| 路由模式 | createWebHistory() | 启用 History 模式(无 #) |
| 路由配置 | routes 数组 | 定义路径与组件的映射关系 |
| 路由出口 | <router-view> | 动态渲染匹配的组件 |
| 导航链接 | <router-link> | 实现无刷新页面跳转 |
| 编程式导航 | router.push() | 通过 JS 控制路由跳转 |
| 路由参数访问 | useRoute().params | 获取动态路由参数(如 /user/:id) |
| 导航守卫 | router.beforeEach() | 控制路由跳转逻辑(如登录验证) |
提示:Vue Router 4 完全支持 Vue 3 的 Composition API,建议使用
useRouter()和useRoute()替代this.$router/this.$route。