Vue Router

Vue Router 是 Vue.js 官方的路由管理工具,用于构建单页面应用 (SPA)。通过 Vue Router,应用可以根据 URL 路径动态加载组件,无需刷新页面,实现流畅的导航和组件展示。以下是 Vue Router 的详细介绍:

1. 基本概念

  • 路由(Route): 路由是 URL 与特定组件的映射关系。每个路由定义了当用户访问某个路径时,应该显示哪个组件。
  • 路由器(Router): 路由器管理所有的路由和导航。Vue Router 通过 vue-router 插件来使用。

2. 安装 Vue Router

可以通过 npm 或 yarn 安装 Vue Router:

npm install vue-router@next
# 或者
yarn add vue-router@next

3. 基本使用

1. 定义路由

首先,在应用中定义 URL 路径与组件之间的关系。每个路由对象至少有两个属性:path(路径)和 component(组件)。

import { createRouter, createWebHistory } from 'vue-router'
import HomeComponent from './components/Home.vue'
import AboutComponent from './components/About.vue'

const routes = [
  { path: '/', component: HomeComponent },
  { path: '/about', component: AboutComponent },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})
2. 在应用中使用路由

在 Vue 组件中,通过 router-view 显示匹配到的路由组件:

<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link>
      <router-link to="/about">About</router-link>
    </nav>
    <router-view></router-view>
  </div>
</template>

在 Vue 应用的 main.js 中,使用 use 方法注册路由:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

createApp(App).use(router).mount('#app')

4. 导航

  • router-link 用于导航到不同的路由。

    <router-link to="/about">Go to About</router-link>
    
  • 编程式导航: 通过代码实现跳转。

    this.$router.push('/about')
    

5. 动态路由

动态路由允许路由匹配 URL 中的动态部分,例如用户 ID 等参数。

const routes = [
  { path: '/user/:id', component: UserComponent },
]

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

<template>
  <div>User ID: {{ $route.params.id }}</div>
</template>

6. 嵌套路由

嵌套路由允许你在一个组件中展示多个层次的视图。例如,用户页面中可以有用户简介和用户文章两个子页面。

const routes = [
  {
    path: '/user/:id',
    component: UserComponent,
    children: [
      { path: 'profile', component: UserProfile },
      { path: 'posts', component: UserPosts },
    ]
  }
]

使用 router-view 来展示嵌套的子组件:

<template>
  <div>
    <h2>User {{ $route.params.id }}</h2>
    <router-view></router-view>
  </div>
</template>

7. 导航守卫

Vue Router 提供了导航守卫(Navigation Guards),用于在路由切换前后执行逻辑,如权限验证、重定向等。

  • 全局前置守卫: 在每次导航前执行。

    router.beforeEach((to, from, next) => {
      if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login')
      } else {
        next()
      }
    })
    
  • 路由独享守卫: 只在某个特定路由中生效。

    const routes = [
      {
        path: '/admin',
        component: AdminComponent,
        beforeEnter: (to, from, next) => {
          if (isAdmin) {
            next()
          } else {
            next('/login')
          }
        }
      }
    ]
    

8. 路由元信息 (meta)

路由对象可以包含 meta 字段,用于存储与路由相关的任意信息。例如,可以在 meta 中标记是否需要认证:

const routes = [
  {
    path: '/dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  }
]

可以通过 to.meta 访问这些信息,在导航守卫中使用:

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

9. 重定向和别名

  • 重定向: 将一个路由重定向到另一个路径。

    const routes = [
      { path: '/home', redirect: '/' }
    ]
    
  • 别名: 给某个路径提供额外的名称。

    const routes = [
      { path: '/profile', component: UserProfile, alias: '/user-profile' }
    ]
    

10. 懒加载

为了提高性能,可以使用懒加载方式按需加载组件:

const routes = [
  {
    path: '/about',
    component: () => import('./components/About.vue')
  }
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值