在前端开发中,路由是构建单页应用程序的核心慨念之一。允许应用根据URL的变化动态地渲染不同的组件或页面。Vue.js提供了官方的路由管理工具——Vue Router。接下来这篇文章将逐步讲解Vue 3 中的路由概念以及使用。
路由其实就是 URL 与应用程序视图之间的映射关系。
在传统的多页应用里面,每次跳转都是向服务器发送请求,服务器返回新的页面的过程。但是在 SPA 中,页面并不会刷新,而是根据 URL 的变化,动态地加载相应的组件,为实现这一效果,就需要路由系统的管理。
Vue Router 的核心概念:介绍 | Vue Router
这个路由器并不是网络服务中用于转发路由的路由器,而是 SPA 中路由系统的核心的控制页面映射的路由器。
它的功能包括:
路由是路径(Path)与组件(compontent)的对应关系。
一个典型的路由定义包括:
在开始之前,需要安装 Vue Router:
npm install vue-router@4
在项目的入口文件(如 router/index.js)中:
import { createRouter, createWebHistory } from 'vue-router';
// 导入需要的组件
import Home from './components/Home.vue';
import About from './components/About.vue';
// 定义路由
const router = [
{ path: '/', component: Home },
{ path: '/about', component: About },
];
// 创建路由器实例
const router = createRouter({
history: createWebHistory(), // 使用 HTML5 模式
router, // 路由配置
});
export default router; // 以 router 暴露出去
在项目的入口文件(如 main.js)中:
import { createApp } from 'vue';
import App from './App.vue';
import router from "./router/index.js"
// 创建并挂载应用
const app = createApp(App);
app.use(router);
app.mount('#app');
在 components 目录下创建 Home.vue 和 About.vue:
首页
关于我们
在 App.vue 中:
使用
首页
跳转到 about 页面
Home 页面将数据传输给 About 页面
首页
跳转到 about 页面
About 页面接受并渲染 Home 的数据
我们通过引入路由并打印路由来获取到传过来的数据(在控制台查看)
关于我们
const router = [
{ path: '/user/:id', component: User },
];
在组件中获取路由参数:
关于我们
定义嵌套路由(在router/index.js)中:
const router = [
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile,
},
{
path: 'posts',
component: UserPosts,
},
],
},
];
在父组件模板中:
用户页面
全局前置守卫:
router.beforeEach((to, from, next) => {
// 例如,验证用户是否已登录
if (to.path === '/protected' && !isLoggedIn()) {
next('/login');
} else {
next();
}
});
路由独享守卫:
const router = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 仅管理员可访问
if (isAdmin()) {
next();
} else {
next('/login');
}
},
},
];
组件内守卫:
通过动态导入实现路由组件的懒加载:
const router = [
{
path: '/about',
component: () => import('./components/About.vue'),
},
];
命名路由:
const router = [
{
path: '/user/:id',
name: 'user',
component: User,
},
];
//在模板中
// 导航到命名路由