Vue 3中的路由(Router)详解

在前端开发中,路由是构建单页应用程序的核心慨念之一。允许应用根据URL的变化动态地渲染不同的组件或页面。Vue.js提供了官方的路由管理工具——Vue Router。接下来这篇文章将逐步讲解Vue 3 中的路由概念以及使用。

一、什么是路由?

路由其实就是 URL 与应用程序视图之间的映射关系。
在传统的多页应用里面,每次跳转都是向服务器发送请求,服务器返回新的页面的过程。但是在  SPA 中,页面并不会刷新,而是根据 URL 的变化,动态地加载相应的组件,为实现这一效果,就需要路由系统的管理。

Vue Router 的核心概念

 Vue Router 的核心概念:介绍 | Vue Router

1.路由器( Router )

这个路由器并不是网络服务中用于转发路由的路由器,而是 SPA 中路由系统的核心的控制页面映射的路由器。
它的功能包括:

  • 监听 URL 的变化
  • 根据定义的 路由规则,映射到对应的组件。
  • 提供导航方法,控制页面跳转。
2.路由(Route)

路由是路径(Path)与组件(compontent)的对应关系。
一个典型的路由定义包括:

  • path:URL当中的路径部分
  • compontent:当路径匹配时要渲染的组件

二、如何在 Vue 3 中使用 Vue Router

1.安装 Vue Router

在开始之前,需要安装 Vue Router:

npm install vue-router@4

2. 创建路由器实例

在项目的入口文件(如 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');

3. 定义路由组件:

在 components 目录下创建 Home.vue 和 About.vue:









4. 使用 显示路由组件

在 App.vue 中:


5. 路由跳转(从 A 页面跳转到 B 页面)

使用 创建导航链接,或者在脚本中使用编程式导航:




6.路由传参(当一个页面跳转到另一个页面时将指定数据也一起传过去)

Home 页面将数据传输给 About 页面




About 页面接受并渲染 Home 的数据

我们通过引入路由并打印路由来获取到传过来的数据(在控制台查看)





三、进阶概念

1. 动态路由匹配(在router/index.js)中:

const router = [
  { path: '/user/:id', component: User },
];

在组件中获取路由参数:





2. 嵌套路由

定义嵌套路由(在router/index.js)中:

const router = [
  {
    path: '/user/:id',
    component: User,
    children: [
      {
        path: 'profile',
        component: UserProfile,
      },
      {
        path: 'posts',
        component: UserPosts,
      },
    ],
  },
];

在父组件模板中:


3. 导航守卫

全局前置守卫:

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');
      }
    },
  },
];

组件内守卫:



4. 懒加载路由

通过动态导入实现路由组件的懒加载:

const router = [
  {
    path: '/about',
    component: () => import('./components/About.vue'),
  },
];

5. 命名路由和命名视图

命名路由:

const router = [
  {
    path: '/user/:id',
    name: 'user',
    component: User,
  },
];

//在模板中