Skip to content
xiaoyang 的头像xiaoyang发布于 2025-02-283,629 字阅读约 12 分钟浏览加载中访客加载中

Vue-Router 组件路由机制 ​

在 Vue 项目中,尽管 index.html 通常只包含一个页面,但通过 Vue-Router 路由管理,我们可以实现多个页面间的跳转和内容切换,从而形成多页面应用。Vue-Router 是 Vue 官方提供的路由管理组件,它可以让我们在单页面应用(SPA)中实现路由的配置和管理。

1. 安装和基础配置 ​

Vue-Router 是 Vue.js 官方推荐的路由解决方案,Vue 3.x 版本要求使用 Vue-Router 4.x。首先,我们需要安装 Vue-Router,并进行基础配置。

1.1 安装 Vue-Router ​

在 Vue 3 项目中,我们可以通过 npm 或 yarn 来安装 Vue-Router:

bash
npm install vue-router@4

1.2 配置路由 ​

我们在 main.ts 文件中配置路由。假设我们有 HomePage, AboutPage, NewsPage 这几个页面组件,在 router 配置中定义相应的路由规则。

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

import HomePage from '@/pages/Home.vue'
import AboutPage from '@/pages/About.vue'
import NewsPage from '@/pages/News.vue'

// 配置路由规则
const routes = [
  { path: '/', redirect: '/home' }, // 默认跳转到首页
  { path: '/home', component: HomePage },
  { path: '/about', component: AboutPage, name: 'about' }, // 命名路由
  { path: '/news', component: NewsPage }
]

// 创建路由器
const router = createRouter({
  history: createWebHistory(), // 使用 history 模式
  routes,
})

const app = createApp(App)

// 加载路由器
app.use(router)

app.mount('#app')

1.3 配置组件中的跳转链接和展示位置 ​

在 Vue 模板中,使用 <router-link> 组件来进行路由跳转,使用 <router-view> 组件来展示路由对应的内容。

vue
<template>
  <div id="app">
    <h1>Hello App!</h1>
    <p>
      <!-- 使用 router-link 组件进行导航 -->
      <router-link to="/home">首页</router-link>
      <router-link :to="{ path:'/about'}">关于</router-link>
      <router-link replace :to="{ name:'news'}">新闻</router-link>
    </p>
    
    <!-- 路由出口 -->
    <div class="content">
      <router-view></router-view>
    </div>
  </div>
</template>

<script lang="ts" setup>
// setup 脚本
</script>

<style scoped>
/* 样式 */
a {
  margin: 10px;
}
.content {
  background: yellowgreen;
  width: 100%;
  height: 400px;
  border: 1px solid #000;
  border-radius: 10px;
}
</style>

2. 路由工作模式 ​

Vue-Router 提供了两种工作模式来管理路由:

2.1 history 模式 ​

  • 在 history 模式下,URL 路径不带 #,与传统的多页面网站一致。
  • 优点:路径干净简洁。
  • 缺点:可能会产生 404 错误,需要后端支持所有路由的重定向。
ts
createRouter({
  history: createWebHistory() // 使用 history 模式
})

2.2 hash 模式 ​

  • 在 hash 模式下,URL 会带有 # 符号,如 http://example.com/#/home。
  • 优点:不依赖后端支持,直接通过前端处理。
  • 缺点:对 SEO 不太友好。
ts
createRouter({
  history: createWebHashHistory() // 使用 hash 模式
})

<router-link> 组件有一个 replace 属性,它可以用来替代浏览器的历史记录。

  • push(默认值):将当前路由推入历史栈,允许浏览器的返回按钮返回到上一个页面。
  • replace:替换当前历史记录,点击浏览器的返回按钮时不会返回到当前页面。
vue
<router-link replace to="/about">关于</router-link>

4. 嵌套路由 ​

嵌套路由使得我们能够在同一页面中展示多个视图,适用于具有层次结构的页面。比如,新闻页面中可能有新闻列表和新闻详情,新闻详情是一个嵌套路由。

4.1 配置嵌套路由 ​

ts
// 定义嵌套路由
const routes = [
  { path: '/', redirect: '/home' },
  { path: '/home', component: HomePage },
  { path: '/about', component: AboutPage },
  { 
    path: '/news', 
    component: NewsPage, 
    name: 'news',
    children: [ // 子路由
      {
        name: 'xinwen1',
        path: '1',
        component: News1
      },
      {
        name: 'xinwen2',
        path: '2',
        component: News2
      }
    ]
  }
]

4.2 子路由的展示 ​

在 NewsPage 组件中,我们使用 <router-view> 来渲染嵌套的子路由。

vue
<template>
  <div class="news">
    <p>新闻列表</p>
    <ul>
      <li><router-link to="/news/1">新闻1</router-link></li>
      <li><router-link to="/news/2">新闻2</router-link></li>
    </ul>

    <div class="news-content">
      <!-- 子路由展示区域 -->
      <router-view></router-view>
    </div>
  </div>
</template>

<script setup>
// setup 脚本
</script>

5. 路由传参 ​

为了使页面动态化,我们经常需要传递参数来展示不同的内容。Vue 提供了两种方式来传递路由参数:query 参数和 params 参数。

5.1 query 传参 ​

使用 URL 的查询字符串来传递参数,类似于传统的 GET 请求。

vue
<!-- 使用 query 传参 -->
<router-link :to="{ path: '/news/1', query: { id: '1', title: '新闻1' } }">新闻1</router-link>

在接收参数的页面中,通过 useRoute 钩子函数获取 query 参数。

ts
import { useRoute } from 'vue-router'

const route = useRoute()
console.log(route.query) // { id: '1', title: '新闻1' }

5.2 params 传参 ​

params 参数通过 URL 中的占位符进行传递,通常用在动态路由中。

ts
// 配置路由时,使用占位符
const routes = [
  {
    path: '/news/:id',
    component: NewsDetail
  }
]
<!-- 传递 params 参数 -->
<router-link :to="{ path: '/news/1' }">新闻1</router-link>

在 NewsDetail.vue 中,通过 useRoute 获取 params 参数:

ts
const route = useRoute()
console.log(route.params) // { id: '1' }

6. 总结 ​

Vue-Router 是 Vue 应用中实现路由管理的核心组件,它为我们提供了便捷的路由配置方式,支持动态页面渲染、嵌套路由、路由传参等功能。通过合理配置路由,Vue 可以实现单页面应用(SPA)中的多页面跳转和内容展示,提升用户体验。

DISCUSSION

评论区

欢迎分享你的思考、补充或问题。

评论加载中…

基于 VitePress 搭建