蓝色天空.知识 · 实践 · 创造
我的收藏
Vue3 教程目录 48章
Vue3 / LEARN BY DOING

路由跳转

核对前端 SPA 路由原理、Vue Router 4 路由表与 History/Hash 模式、RouterView/RouterLink 声明式导航、useRoute 字符串参数转换及文章详情与 404 回退实测。

学完这一章,你能够

  • 核对前端 SPA 路由原理、Vue Router 4 路由表与 History/Hash 模式、RouterView/RouterLink 声明式导航、useRoute 字符串参数转换及文章详情与 404 回退实测。

前端路由原理与 Vue Router 核心概念

传统多页站点点击超链接后会向服务端重新请求整份 HTML,伴随整页刷新与白屏闪烁;Vue Router 实现的前端路由在 URL 变化时拦截导航,由 JavaScript 在客户端即时切换对应视图组件,带来接近原生应用的流畅体验。其四大核心构件包括:映射路径与组件的路由表 `routes`、承载当前匹配组件的出口 `<RouterView />`、声明式导航组件 `<RouterLink to="...">`,以及携带路径参数的动态路由 `/post/:id`。

安装注册、路由模式与 RouterView/RouterLink

若初始化脚手架时未勾选路由模块,可执行 `npm install vue-router@4` 安装。随后在 `src/router/index.js` 中调用 `createRouter` 注册首页 `/`(`HomeView`)与动态详情页 `/post/:id`(使用 `() => import('../views/PostView.vue')` 按需懒加载并拆包)。路由历史模式分为两类:`createWebHistory()` 生成简洁路径 `/post/1`,上线时需服务端配置回退规则;`createWebHashHistory()` 在路径中带有 `#`(如 `#/post/2`),无需额外服务端重写。本站离线 Chromium 在本地回环服务中同时实测了 History 路径 `/post/1` 与 Hash 片段 `#/post/2`。

在入口 `main.js` 中 `app.use(router)` 注册后,在 `App.vue` 里保留公共 `<NavBar />` 并放置 `<RouterView />` 路由出口,URL 匹配 `/` 渲染首页、匹配 `/post/1` 渲染详情页。页面内跳转应使用 `<RouterLink>`(推荐命名路由 `:to="{ name: 'post', params: { id: article.id } }"`)替代原生 `<a>` 标签,避免触发整页重新加载。本站实测点击文章卡片跳转 `/post/1` 并返回 `/` 全程未重载文档(页面挂载标记 `SPA-NONCE-43` 始终保留,懒加载回调按需执行 `1` 次)。

useRoute 参数类型与博客详情页实战

在详情页 `PostView.vue` 中调用 `useRoute()` 读取当前路由对象,通过 `route.params.id` 获取动态路径参数。需要特别留意:`route.params.id` 永远是字符串类型(例如访问 `/post/3` 得到 `'3'` 而非数字 `3`),与数值型文章 ID 比对前必须使用 `Number(route.params.id)` 或 `parseInt` 显式转换。本站实测访问 `/post/1` 时捕获参数原始值为 `'1'`(`typeof === 'string'`),转换为数字 `1` 后精确匹配首篇文章。

实战改造分两步完成:先为 `BlogCard.vue` 增加 `id: Number` prop 并用 `<RouterLink>` 包裹整个卡片;再编写 `PostView.vue`,依据转换后的 ID 查找文章,命中时用 `v-html` 渲染受信任的 HTML 正文(务必切记绝不可将 `v-html` 用于未清洗的用户输入,以防 XSS 注入),未命中时渲染“文章不存在”与返回首页链接。本站离线 Chromium 实测:进入 `/post/1` 渲染标题 `Vue3 入门完全指南` 及两处正文二级标题 `['为什么学 Vue3?', 'ref 与 reactive']`;进入 `/post/999` 渲染 `文章不存在` 与 `找不到 ID 为 999 的文章`,点击返回链接无刷新回到 `/`。

Vue Router 4 核心概念与对应语法

概念核心作用常用代码形式
路由映射配置表集中定义 URL 路径、路由名称与页面组件(或懒加载函数)的对应关系routes 数组
动态视图渲染占位容器承载当前 URL 匹配到的页面组件,常位于 App.vue 主区域内<RouterView />
声明式无刷新跳转组件替代传统 <a> 标签,拦截点击并以客户端路由切换视图<RouterLink to="...">
含路径参数的路由模式用冒号占位符捕获文章 ID 等动态片段并写入 route.params/post/:id

离线 Chromium 本地回环服务实测 SPA 路由跳转、动态参数 /post/:id、v-html 与 404 回退

含完整源码 · 289 行
展开查看收起
python
"""Offline Playwright Chromium lab for Vue 3 Ch 43: Vue Router SPA navigation, dynamic params & 404."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from playwright.sync_api import sync_playwright


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 Router Lab</title>
</head>
<body>
  <header class="navbar">
    <a href="/" data-router-link="/" class="logo">BlueSky Blog</a>
    <nav>
      <a href="/" data-router-link="/">首页</a>
      <a href="/post/999" data-router-link="/post/999" id="link-404">不存在文章</a>
    </nav>
  </header>
  <main id="router-view"></main>

<script>
window.__mountNonce = 'SPA-NONCE-43';
let lazyLoadCount = 0;

const articles = [
  {
    id: 1,
    title: 'Vue3 入门完全指南',
    summary: '从零开始学习 Vue3 组合式 API',
    category: 'Vue',
    date: '2024-05-10',
    content: '<h2>为什么学 Vue3?</h2><p>Vue3 是目前最流行的前端框架之一。</p><h2>ref 与 reactive</h2><p>推荐统一使用 ref 管理状态。</p>'
  },
  {
    id: 2,
    title: 'JS 异步编程详解',
    summary: '搞懂 Promise 和 async/await',
    category: 'JavaScript',
    date: '2024-05-08',
    content: '<h2>什么是异步?</h2><p>JS 是单线程的,异步操作不会阻塞主线程。</p>'
  }
];

function HomeView() {
  return `
    <div class="home">
      <h1>最新文章</h1>
      <div class="article-grid">
        ${articles
          .map(
            (a) => `
          <a href="/post/${a.id}" data-router-link="/post/${a.id}" class="card-link" data-id="${a.id}">
            <div class="card">
              <span class="tag">${a.category}</span>
              <h3>${a.title}</h3>
              <p>${a.summary}</p>
            </div>
          </a>`
          )
          .join('')}
      </div>
    </div>`;
}

function PostView(route) {
  const rawParam = route.params.id;
  const id = Number(rawParam);
  const article = articles.find((a) => a.id === id);
  window.__lastRouteParam = { raw: rawParam, rawType: typeof rawParam, numeric: id };
  if (!article) {
    return `
      <div class="post-view">
        <div class="not-found">
          <h2>文章不存在</h2>
          <p class="not-found-msg">找不到 ID 为 ${id} 的文章</p>
          <a href="/" data-router-link="/" class="back-link">返回首页</a>
        </div>
      </div>`;
  }
  return `
    <div class="post-view">
      <article>
        <span class="category-tag">${article.category}</span>
        <h1>${article.title}</h1>
        <time>${article.date}</time>
        <div class="content">${article.content}</div>
        <a href="/" data-router-link="/" class="back-link">← 返回首页</a>
      </article>
    </div>`;
}

const routes = [
  { path: '/', name: 'home', component: HomeView },
  {
    path: '/post/:id',
    name: 'post',
    component: async () => {
      lazyLoadCount++;
      return PostView;
    }
  }
];

function matchRoute(pathname) {
  if (pathname === '/') return { route: routes[0], params: {} };
  const m = pathname.match(/^\/post\/([^/]+)$/);
  if (m) return { route: routes[1], params: { id: decodeURIComponent(m[1]) } };
  return { route: routes[1], params: { id: 'NaN' } };
}

async function renderPath(pathname) {
  const matched = matchRoute(pathname);
  const compOrLoader = matched.route.component;
  const viewFn = matched.route.name === 'post' ? await compOrLoader() : compOrLoader;
  const routeObj = { path: pathname, name: matched.route.name, params: matched.params };
  document.getElementById('router-view').innerHTML = viewFn(routeObj);
}

async function push(pathname) {
  window.history.pushState({}, '', pathname);
  await renderPath(pathname);
}

// Intercept declarative RouterLink clicks (no full page reload)
document.addEventListener('click', (e) => {
  const link = e.target.closest('a[data-router-link]');
  if (!link) return;
  e.preventDefault();
  push(link.getAttribute('data-router-link'));
});

window.addEventListener('popstate', () => {
  renderPath(window.location.pathname);
});

// Compare createWebHistory vs createWebHashHistory URL format
window.__routerLab = {
  testHashMode(id) {
    window.location.hash = `#/post/${id}`;
    return window.location.hash;
  },
  getStats() {
    return {
      mountNonce: window.__mountNonce,
      pathname: window.location.pathname,
      lazyLoadCount,
      lastRouteParam: window.__lastRouteParam
    };
  }
};

renderPath(window.location.pathname);
</script>
</body>
</html>
"""


class SpaHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        body = HTML.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, format, *args):
        pass


def main():
    server = HTTPServer(("127.0.0.1", 0), SpaHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    base_url = f"http://127.0.0.1:{port}"

    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                page = browser.new_page()
                page.goto(f"{base_url}/")
                home_h1 = page.text_content("#router-view h1")
                card_count = page.locator(".card-link").count()
                hash_sample = page.evaluate("window.__routerLab.testHashMode(2)")

                # Click BlogCard 1 via RouterLink (SPA navigation without reload)
                page.click('.card-link[data-id="1"]')
                page.wait_for_selector("article h1")
                post1_title = page.text_content("article h1")
                post1_h2s = page.eval_on_selector_all("article .content h2", "els => els.map(e => e.textContent)")
                stats1 = page.evaluate("window.__routerLab.getStats()")

                # Back to home via RouterLink
                page.click(".back-link")
                page.wait_for_selector(".article-grid")
                home_after_back = page.evaluate("window.location.pathname")

                # Navigate to missing post /post/999 -> not-found view
                page.click("#link-404")
                page.wait_for_selector(".not-found")
                not_found_h2 = page.text_content(".not-found h2")
                not_found_msg = page.text_content(".not-found-msg")
                stats404 = page.evaluate("window.__routerLab.getStats()")

                # Return home from 404
                page.click(".not-found .back-link")
                page.wait_for_selector(".article-grid")
                final_path = page.evaluate("window.location.pathname")
            finally:
                browser.close()
    finally:
        server.shutdown()
        server.server_close()

    actuals = {
        "router_history_and_hash_modes": {
            "home_h1": home_h1,
            "card_count": card_count,
            "history_path": stats1["pathname"],
            "hash_sample": hash_sample,
        },
        "router_link_spa_navigation_no_reload": {
            "mount_nonce_preserved": stats1["mountNonce"],
            "lazy_loads_after_post1": stats1["lazyLoadCount"],
            "home_after_back": home_after_back,
        },
        "use_route_params_string_and_post_view": {
            "param_raw": stats1["lastRouteParam"]["raw"],
            "param_type": stats1["lastRouteParam"]["rawType"],
            "param_numeric": stats1["lastRouteParam"]["numeric"],
            "post1_title": post1_title,
            "post1_h2s": post1_h2s,
        },
        "post_not_found_and_back_home": {
            "not_found_path": stats404["pathname"],
            "not_found_h2": not_found_h2,
            "not_found_msg": not_found_msg,
            "final_path": final_path,
        },
    }
    expected = {
        "router_history_and_hash_modes": {
            "home_h1": "最新文章",
            "card_count": 2,
            "history_path": "/post/1",
            "hash_sample": "#/post/2",
        },
        "router_link_spa_navigation_no_reload": {
            "mount_nonce_preserved": "SPA-NONCE-43",
            "lazy_loads_after_post1": 1,
            "home_after_back": "/",
        },
        "use_route_params_string_and_post_view": {
            "param_raw": "1",
            "param_type": "string",
            "param_numeric": 1,
            "post1_title": "Vue3 入门完全指南",
            "post1_h2s": ["为什么学 Vue3?", "ref 与 reactive"],
        },
        "post_not_found_and_back_home": {
            "not_found_path": "/post/999",
            "not_found_h2": "文章不存在",
            "not_found_msg": "找不到 ID 为 999 的文章",
            "final_path": "/",
        },
    }
    cases = [
        {"name": k, "expected": expected[k], "actual": actuals[k], "passed": actuals[k] == expected[k]}
        for k in expected
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对无刷新跳转保留页面挂载标记、History 与 Hash 路径格式、route.params.id 字符串转数字匹配详情页正文以及 /post/999 显示文章不存在并返回首页。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a801.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Vue3

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip

下载课程关联工程包:Vue3

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a809.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

createWebHistory 使用标准路径(如 /post/1),直接刷新子路径需服务端将未知路径回退到 index.html;createWebHashHistory 通过 # 后片段切换路由,不发给服务端因此零配置即可运行。URL 路径解析出的 params 值一律是字符串,与严格相等 === 比较数字 ID 前必须先转为数值。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习