Vue Router 基础:前端路由使用指南

Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。以下是核心使用步骤:


1. 安装与引入
npm install vue-router@4  # Vue 3 对应版本

在入口文件中初始化:

import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: []  // 路由配置将在下一步定义
})

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


2. 定义路由配置

/src/router/index.js 中配置路由映射:

const routes = [
  {
    path: '/',          // 路径
    name: 'Home',       // 路由名称
    component: () => import('./views/Home.vue')  // 懒加载组件
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('./views/About.vue')
  }
]


3. 路由导航

两种导航方式:

  • 声明式导航(推荐)
    使用 <router-link> 组件:

    <template>
      <router-link to="/">首页</router-link>
      <router-link :to="{ name: 'About' }">关于</router-link>
    </template>
    

  • 编程式导航
    在 JavaScript 中控制跳转:

    // 在 Vue 组件中
    this.$router.push('/about')             // 跳转到路径
    this.$router.push({ name: 'Home' })     // 按路由名称跳转
    


4. 渲染路由组件

在根组件中添加 <router-view> 作为路由出口:

<template>
  <div id="app">
    <nav>...</nav>
    <router-view></router-view>  <!-- 路由组件将在此渲染 -->
  </div>
</template>


5. 动态路由与参数

处理动态参数(如用户 ID):

// 路由配置
{
  path: '/user/:id',
  name: 'User',
  component: () => import('./views/User.vue')
}

在目标组件中获取参数:

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


6. 导航守卫

控制路由跳转逻辑:

router.beforeEach((to, from, next) => {
  if (to.name === 'Admin' && !isAuthenticated) {
    next('/login')  // 重定向到登录页
  } else {
    next()          // 允许导航
  }
})


关键概念总结

功能 实现方式
路由跳转 <router-link>$router.push()
路由渲染 <router-view>
参数传递 path: '/user/:id' + $route.params
权限控制 导航守卫 (beforeEach 等)

提示:使用路由时需注意:

  1. 路由组件通常放在 /views/ 目录
  2. 嵌套路由通过 children 属性配置
  3. 404 页面可用 path: '/:catchAll(.*)' 捕获

通过以上步骤,即可实现前端路由管理,构建无刷新跳转的 SPA 应用。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐