Vue Router 详解

avatar
作者
筋斗云
阅读量:0

Vue Router 是 Vue.js 生态系统中的一个核心插件,旨在帮助开发者轻松地在单页面应用程序 (SPA) 中实现路由功能。在这篇博客中,我们将深入探讨 Vue Router 的各个方面,包括其基本概念、配置和高级用法。

1. 什么是 Vue Router?

Vue Router 是 Vue.js 的官方路由管理器。它与 Vue.js 无缝集成,能够帮助你构建单页面应用程序,并且支持以下特性:

  • 嵌套路由:允许在一个路由组件内定义子路由。
  • 动态路由匹配:使用路径参数实现动态路由。
  • 模块化、基于组件的路由配置:路由与 Vue 组件紧密结合,配置简洁直观。
  • 路由参数:支持在路径中定义参数并在组件中使用。
  • 路由守卫:提供多种导航守卫钩子,允许在路由跳转前后进行拦截和处理。
  • 路由元信息:可以为路由添加自定义元数据,以便在导航守卫或组件中使用。
  • 滚动行为控制:控制路由切换时页面滚动位置。
  • 历史模式与哈希模式:支持使用 HTML5 History API 或 URL 哈希模式来实现路由。

2. 安装 Vue Router

首先,确保你已经安装了 Vue.js。然后,可以通过以下方式安装 Vue Router:

npm install vue-router 

在你的 Vue 项目中,创建一个 router 文件夹,并在其中创建 index.js 文件,用于配置路由。

3. 基本使用

创建路由配置

router/index.js 文件中,定义你的路由配置:

import { createRouter, createWebHistory } from 'vue-router' import Home from '../views/Home.vue' import About from '../views/About.vue'  const routes = [   {     path: '/',     name: 'Home',     component: Home   },   {     path: '/about',     name: 'About',     component: About   } ]  const router = createRouter({   history: createWebHistory(process.env.BASE_URL),   routes })  export default router 

在 Vue 实例中使用路由

在你的 main.js 文件中,导入并使用路由:

import { createApp } from 'vue' import App from './App.vue' import router from './router'  createApp(App).use(router).mount('#app') 

创建视图组件

views 文件夹中,创建对应的视图组件,比如 Home.vueAbout.vue

<!-- Home.vue --> <template>   <div>     <h1>Home</h1>   </div> </template>  <script> export default {   name: 'Home' } </script> 
<!-- About.vue --> <template>   <div>     <h1>About</h1>   </div> </template>  <script> export default {   name: 'About' } </script> 

使用 <router-link><router-view>

在你的 App.vue 中,使用 <router-link> 进行导航,使用 <router-view> 显示匹配的组件:

<template>   <div id="app">     <nav>       <router-link to="/">Home</router-link>       <router-link to="/about">About</router-link>     </nav>     <router-view/>   </div> </template> 
函数介绍:
  • createRouter: 用于创建路由实例,接收一个配置对象作为参数。
    • 参数
      • history:用于定义路由模式,常用的有 createWebHistory()createWebHashHistory()
      • routes:定义路由规则的数组。
  • createWebHistory: 创建 HTML5 模式的历史记录。
    • 参数
      • base:可选,应用的基路径。
  • createWebHashHistory: 创建哈希模式的历史记录(URL 带有 #)。
    • 参数
      • base:可选,应用的基路径。

4. 嵌套路由

Vue Router 支持嵌套路由,这对于复杂的应用程序非常有用。

import Home from '../views/Home.vue' import Profile from '../views/Profile.vue' import Settings from '../views/Settings.vue'  const routes = [   {     path: '/',     component: Home,     children: [       {         path: 'profile',         component: Profile       },       {         path: 'settings',         component: Settings       }     ]   } ] 

在视图组件中使用 <router-view> 渲染子路由:

<!-- Home.vue --> <template>   <div>     <h1>Home</h1>     <router-view/>   </div> </template> 

5. 动态路由匹配

动态路由匹配允许你在路径中使用变量。

import User from '../views/User.vue'  const routes = [   {     path: '/user/:id',     component: User   } ] 

在组件中,你可以通过 this.$route.params 访问动态参数:

<template>   <div>     <h1>User {{ $route.params.id }}</h1>   </div> </template>  <script> export default {   name: 'User' } </script> 
函数介绍:
  • $route.params: 存储路由参数的对象,可以通过 this.$route.params.id 获取路径中的 id 参数。

6. 路由守卫

路由守卫允许你在导航前进行一些操作,如权限验证或数据获取。

全局守卫

router.beforeEach((to, from, next) => {   if (to.path === '/protected' && !isAuthenticated()) {     next('/login')   } else {     next()   } }) 

路由独享守卫

const routes = [   {     path: '/protected',     component: Protected,     beforeEnter: (to, from, next) => {       if (!isAuthenticated()) {         next('/login')       } else {         next()       }     }   } ] 

组件内守卫

export default {   beforeRouteEnter (to, from, next) {     // 在进入路由前调用     next(vm => {       // 在导航被确认时调用     })   },   beforeRouteUpdate (to, from, next) {     // 在当前路由改变但该组件被复用时调用     next()   },   beforeRouteLeave (to, from, next) {     // 导航离开该组件的对应路由时调用     next()   } } 
函数介绍:
  • beforeEach: 注册一个全局前置守卫,在每次导航前调用。
    • 参数
      • to:即将进入的目标路由对象。
      • from:当前导航正要离开的路由。
      • next:函数,必须调用该方法来 resolve 这个钩子,执行效果依赖 next 方法的调用参数。
  • beforeEnter: 注册一个路由独享的守卫,只在进入该路由前调用。
    • 参数
      • to:即将进入的目标路由对象。
      • from:当前导航正要离开的路由。
      • next:函数,必须调用该方法来 resolve 这个钩子,执行效果依赖 next 方法的调用参数。
  • beforeRouteEnter: 组件内守卫,在路由进入前调用。
    • 参数
      • to:即将进入的目标路由对象。
      • from:当前导航正要离开的路由。
      • next:函数,必须调用该方法来 resolve 这个钩子,执行效果依赖 next 方法的调用参数。
  • beforeRouteUpdate: 组件内守卫,在当前路由改变但该组件被复用时调用。
    • 参数
      • to:即将进入的目标路由对象。
      • from:当前导航正要离开的路由。
      • next:函数,必须调用该方法来 resolve 这个钩子,执行效果依赖 next 方法的调用参数。
  • beforeRouteLeave: 组件内守卫,在导航离开该组件的对应路由时调用。
    • 参数
      • to:即将进入的目标路由对象。
      • from:当前导航正要离开的路由。
      • next:函数,必须调用该方法来 resolve 这个钩子,执行效果依赖 next 方法的调用参数。

  1. 路由元信息

路由元信息可以帮助你在路由配置中定义自定义的数据。

const routes = [   {     path: '/admin',     component: Admin,     meta: { requiresAuth: true }   } ]  router.beforeEach((to, from, next) => {   if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated()) {     next('/login')   } else {     next()   } }) 
函数介绍:
  • to.matched: 一个数组,包含了导航到的路由记录(包括嵌套路由)。
  • some: 数组方法,用于判断是否有至少一个元素满足条件。

8. 滚动行为控制

你可以在路由配置中定义滚动行为,以实现页面切换时的滚动位置控制。

const router = createRouter({   history: createWebHistory(process.env.BASE_URL),   routes,   scrollBehavior (to, from, savedPosition) {     if (savedPosition) {       return savedPosition     } else {       return { top: 0 }     }   } }) 
函数介绍:
  • scrollBehavior: 一个函数,用于控制路由切换时的滚动行为。
    • 参数
      • to:目标路由对象。
      • from:离开的路由对象。
      • savedPosition:当且仅当 popstate 导航 (通过浏览器的前进/后退按钮触发) 时才可用。

9. 历史模式与哈希模式

Vue Router 默认使用哈希模式 (URL 中带有 #),你也可以选择使用 HTML5 的历史模式。

哈希模式

const router = createRouter({   history: createWebHashHistory(),   routes }) 

历史模式

const router = createRouter({   history: createWebHistory(),   routes }) 
函数介绍:
  • createWebHashHistory: 创建哈希模式的历史记录实例。
    • 参数
      • base:可选,应用的基路径。
  • createWebHistory: 创建 HTML5 模式的历史记录实例。
    • 参数
      • base:可选,应用的基路径。

结论

Vue Router 是一个功能强大且灵活的路由管理器,能够帮助你轻松地构建复杂的单页面应用程序。通过本文的介绍,你应该已经掌握了从基础到高级的各种用法。希望这篇博客能够帮助你更好地理解和使用 Vue Router,在你的 Vue.js 项目中实现优雅的路由管理。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!