1. 路由是什么?为什么需要它?

        前面讲了单个组件页面,我们接下来想象一下传统网站:点击导航菜单,浏览器刷新整个页面,等待加载... 这种体验在如今已经过时了。而路由就是实现"单页面应用(SPA)"的关键技术。

核心概念:路由就是 URL 路径与 Vue 组件的映射关系。当 URL 变化时,自动切换显示对应的组件,无需刷新页面。

2. Vue 3 路由基础配置

2.1 创建路由实例

// router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/pages/Home.vue'
import News from '@/pages/News.vue'
import About from '@/pages/About.vue'

const router = createRouter({
  history: createWebHistory(),  // 创建history模式路由
  routes: [                     // 路由规则数组
    {
      path: '/home',           // 访问路径
      component: Home          // 对应的组件
    },
    {
      path: '/about',
      component: About
    }
  ]
})

export default router

2.2 在 main.ts 中注册

// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'

const app = createApp(App)
app.use(router)  // 注册路由
app.mount('#app')

2.3 在组件中使用

<!-- App.vue -->
<template>
  <div class="app">
    <h2 class="title">Vue路由测试</h2>
    
    <!-- 导航区:RouterLink相当于a标签 -->
    <div class="navigate">
      <RouterLink to="/home" active-class="active">首页</RouterLink>
      <RouterLink to="/news" active-class="active">新闻</RouterLink>
      <RouterLink to="/about" active-class="active">关于</RouterLink>
    </div>
    
    <!-- 展示区:路由组件在这里渲染 -->
    <div class="main-content">
      <RouterView></RouterView>
    </div>
  </div>
</template>

<script lang="ts" setup name="App">
import { RouterLink, RouterView } from 'vue-router'  
</script>

3. 重要注意事项

3.1 文件组织规范

  • 路由组件 → /pages 或 /views 目录

  • 普通组件 → /components 目录

这样划分让项目结构更清晰,便于维护。

3.2 路由组件的生命周期:理解"卸载与重建"

这是路由的核心特性之一,通过一个例子来理解:

<!-- Home.vue -->
<template>
  <div>
    <h3>首页</h3>
    <p>计数器: {{ count }}</p>
    <button @click="count++">+1</button>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const count = ref(0)

onMounted(() => {
  console.log('Home组件被挂载了')
})

onUnmounted(() => {
  console.log('Home组件被卸载了')
})
</script>

实际场景演示

  1. 初始状态:访问 /home,控制台输出:Home组件被挂载了

  2. 切换路由:点击"新闻"跳转到 /news

  3. 发生了什么

    • 控制台输出:Home组件被卸载了

    • Home 组件从内存中完全移除

    • count 数据被重置为 0

  4. 返回首页:再次点击"首页"

  5. 重新创建

    • 控制台再次输出:Home组件被挂载了

    • count 重新初始化为 0

为什么这样设计?

// 路由组件切换的底层逻辑简化版
function switchRoute(newPath) {
  // 1. 卸载当前显示的组件
  currentComponent.unmount()
  
  // 2. 清理所有相关数据
  clearAllData()
  
  // 3. 根据新路径找到对应组件
  const newComponent = findComponent(newPath)
  
  // 4. 重新挂载新组件
  newComponent.mount()
}

带来的影响

优点 缺点
内存管理更高效 组件状态无法保持
避免内存泄漏 每次切换都重新初始化
确保数据纯净  用户体验可能受影响

实际开发建议

  • 需要保持状态时,使用 keep-alive 包裹

  • 重要数据考虑存储在 Vuex/Pinia 中

  • 表单数据考虑使用本地存储临时保存

4. 路由的两种工作模式

4.1 History 模式

const router = createRouter({
  history: createWebHistory(),  // 使用History API
  routes: [...]
})

特点

  • URL美观:http://domain.com/home

  • 需要服务器配合(Nginx配置)

  • SEO更友好

4.2 Hash 模式

const router = createRouter({
  history: createWebHashHistory(),  // 使用URL hash
  routes: [...]
})

特点

  • URL带#:http://domain.com/#/home

  • 无需服务器配置

  • 兼容性极好

为什么说Hash模式更"稳定"?

Hash模式之所以稳定,是因为它完全在前端处理路由,不依赖服务器配置:

# History模式需要Nginx配置
location / {
  try_files $uri $uri/ /index.html;
}
# Hash模式无需任何配置,开箱即用

对于新手或快速原型开发,Hash模式可以避免部署时的各种路径问题。

5. RouterLink 的两种写法

5.1 字符串写法(简单直接)

vue

<RouterLink to="/home" active-class="active">首页</RouterLink>

5.2 对象写法(更灵活)

vue

<RouterLink :to="{ path: '/home' }" active-class="active">首页</RouterLink>

active-class 会自动在激活的链接上添加样式,便于用户识别当前页面。

6. 命名路由:让跳转更智能

6.1 给路由起个名字

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      name: 'zhuye',      // 路由名称
      path: '/home',      // 访问路径  
      component: Home
    },
    {
      name: 'xinwen',
      path: '/news',
      component: News,
    },
    {
      name: 'guanyu',
      path: '/about',
      component: About
    }
  ]
})

6.2 使用命名路由跳转

vue

<!-- 传统写法:需要知道完整路径 -->
<RouterLink to="/news/detail">查看详情</RouterLink>

<!-- 命名路由:只需知道路由名 -->
<RouterLink :to="{ name: 'guanyu' }">关于我们</RouterLink>

优势

  • 路径修改时,只需改一处配置

  • 跳转时不用关心具体路径

  • 配合参数传递更便捷

7. 嵌套路由:构建复杂页面布局

7.1 配置子路由

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      name: 'zhuye',
      path: '/home',
      component: Home
    },
    {
      name: 'xinwen',
      path: '/news',
      component: News,
      children: [                    // 子路由配置
        {
          name: 'xiang',
          path: 'detail',           // 注意:不要以/开头
          component: Detail
        }
      ]
    }
  ]
})

7.2 在父组件中预留路由出口

vue

<!-- News.vue -->
<template>
  <div class="news">
    <!-- 新闻列表 -->
    <nav class="news-list">
      <RouterLink 
        v-for="news in newsList" 
        :key="news.id" 
        :to="{ path: '/news/detail' }"
      >
        {{ news.name }}
      </RouterLink>
    </nav>
    
    <!-- 子路由组件在这里渲染 -->
    <div class="news-detail">
      <RouterView/>
    </div>
  </div>
</template>

7.3 访问嵌套路由

访问URL:/news/detail

路径解析

  • /news → 加载 News 组件

  • detail → 在 News 组件的 <RouterView> 中加载 Detail 组件

Vue 2 vs Vue 3 路由区别

特性 Vue 2 + Vue Router 3 Vue 3 + Vue Router 4
导入方式 import VueRouter from 'vue-router' import { createRouter } from 'vue-router'
创建实例 new VueRouter({}) createRouter({})
历史模式 mode: 'history' history: createWebHistory()
组合式API 不支持 完美支持

核心变化:Vue 3 路由采用函数式创建,更符合组合式API的设计理念。

实战建议

  1. 开发阶段:使用 History 模式,体验更好。

  2. 生产部署

    • 有运维支持 → History + Nginx 配置

    • 简单项目/静态托管 → Hash 模式更省心

  3. 项目规范:统一使用命名路由,提高代码可维护性

通过本章学习,你已经掌握了 Vue Router 的核心概念和基础用法。下一章我们将深入探讨路由传参、编程式导航等高级特性,让你的应用交互更加丰富!

Logo

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

更多推荐