第6章 路由与组件通信

第 6 节 / 共 17 节 课程:前后端穿透

单页应用只有一个 index.html,但用户感觉在“换页面”。这件事由前端路由完成:URL 变,路由表匹配到组件,组件替换 router-view 的内容,页面不整体刷新。

URL 是前端的第一层路由表浏览器地址/course/1/chapter/010100?tab=quiz/course/:idCourseView/chapter/:codeChapterView嵌套?tab=quizquery 控制页签params 适合资源标识(课程 id、章节 code);query 适合筛选、分页、页签。刷新页面还能还原状态,才算真正会用路由。
图 6-1 路由匹配、嵌套与查询参数

6.1 安装与最小路由

npm install vue-router@4
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Course from '../views/Course.vue'
 
const routes = [
{ path: '/', name: 'home', component: Home },
{ path: '/course/:id', name: 'course', component: Course }
]
 
export default createRouter({
    history: createWebHistory(),
    routes
})
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
 
createApp(App).use(router).mount('#app')
<!-- App.vue -->
<template>
  <SiteHeader />
  <router-view />
</template>

6.2 声明式导航与编程式导航

模板里用 router-link,它会生成 a 标签但不会刷新页面。JS 里用 router.push。

<router-link to="/course/39">前后端穿透</router-link>
<router-link :to="{ name: 'course', params: { id: 39 } }">课程</router-link>
 
<button @click="router.push('/course/39')">进入</button>
 
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
</script>

6.3 params 与 query

方式URL 示例读取适合
params/course/39route.params.id资源标识,必须存在
query/course/39?tab=quiz&page=2route.query.tab筛选、分页、页签
<script setup>
import { useRoute } from 'vue-router'
import { computed } from 'vue'
 
const route = useRoute()
const courseId = computed(() => Number(route.params.id))
const tab = computed(() => route.query.tab || 'intro')
</script>

注意:route.params.id 是字符串。要比较数字,先 Number();否则 1 === '1' 永远是 false。

6.4 嵌套路由

课程页里可能还有“简介 / 目录 / 讨论”三个子页。用 children 配置,子路由渲染在父组件的 router-view 里。

{
    path: '/course/:id',
    component: CourseLayout,
    children: [
    { path: '', redirect: 'intro' },
    { path: 'intro', component: CourseIntro },
    { path: 'chapters', component: CourseChapters }
    ]
}
<!-- CourseLayout.vue -->
<template>
  <h1>课程 {{ $route.params.id }}</h1>
  <nav>
    <router-link :to="introPath">简介</router-link>
    <router-link :to="chaptersPath">目录</router-link>
  </nav>
  <router-view />
</template>
 
<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
 
const route = useRoute()
const base = computed(() => '/course/' + route.params.id)
const introPath = computed(() => base.value + '/intro')
const chaptersPath = computed(() => base.value + '/chapters')
</script>

动态路径用 computed 先算好,模板里只绑变量。这样既避免在模板里拼字符串,也方便以后统一改前缀。

6.5 路由守卫

有些页面必须登录。全局前置守卫适合做统一判断:

router.beforeEach((to) => {
    const user = localStorage.getItem('user')
    if (to.meta.requiresAuth && !user) {
        return { name: 'login', query: { redirect: to.fullPath } }
    }
})
{ path: '/admin', component: Admin, meta: { requiresAuth: true } }
前端守卫只是体验,不是安全边界。真正的权限必须由后端接口再判断一次;否则用户改 localStorage 就能进后台。

6.6 组件通信的几种方式

场景方式注意
父子props / emit最常用,优先
跨多层provide / inject适合主题、当前用户等全局但不变的数据
任意组件状态库(Pinia)适合登录态、购物车、复杂共享状态
URL 状态route params/query可刷新、可分享、可后退

不要一上来就上 Pinia。父子能解决就用 props;跨层用 provide/inject;真正需要全局读写再上状态库。

// 祖先
provide('courseId', courseId)
 
// 后代
const courseId = inject('courseId')

6.7 一个完整的路由表

const routes = [
{ path: '/', component: Home },
{ path: '/login', component: Login }, {
    path: '/course/:id',
    component: CourseLayout,
    children: [
    { path: '', redirect: 'intro' },
    { path: 'intro', component: CourseIntro },
    { path: 'chapters', component: CourseChapters }
    ]
},
{ path: '/chapter/:courseId/:code', component: ChapterView },
{ path: '/admin', component: Admin, meta: { requiresAuth: true } },
{ path: '/:pathMatch(.*)*', component: NotFound }
]

6.8 本章练习

  1. 给课程页加“简介 / 目录”两个子路由,刷新后仍停留在当前子页。
  2. 做一个 404 页面,访问不存在的路径时显示,并给出返回首页的链接。
  3. 给后台页面加 requiresAuth,未登录时跳转登录并带上 redirect。

下一章把页面和后端接起来:axios、接口契约、错误处理、跨域。