蓝色天空网mbsky.com · 知识 · 实践 · 创造Vue3 · 本地阅读预览
教程 / 前端开发 / Vue3

Vue3 路由

系统涵盖 Vue Router v4 的 SPA 映射原理、嵌套路由、安装配置、动态参数与 404、导航守卫、编程式导航及全套核心 API 对照表,并附离线回环 Chromium 实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

单页应用路由原理与嵌套视图结构

Vue Router(Vue 3 对应 v4 版本)负责在单页 Web 应用(SPA)中建立 URL 路径与组件的映射:当用户在应用内切换路由时,浏览器地址栏随之更新而无需整页刷新。在工程中通常通过 `vue-router` 库实现路由注册、导航链接与视图出口。

典型的中后台应用常采用两层嵌套路由结构:顶层 `App.vue` 的 `<router-view>` 渲染独立页面(如 `Login.vue`)或主框架 `Layout.vue`;`Layout.vue` 内部再嵌套第二个 `<router-view>` 渲染 `Dashboard.vue`、`User.vue`、`Setting.vue` 等子页面,使页头、侧边栏与页脚持久化保留;未匹配路径则兜底进入 `page404.vue`。本站离线回环 Chromium 实测验证:从 `/home/dashboard` 切换至 `/home/setting` 时 `route.matched` 深度为 `2`,外层 `#layout-shell` DOM 节点引用保持同一对象(`shell_preserved === true`),同时命名视图 `left` 随子路由自动切换。

安装与 9 步基本应用

在 Vue 3 项目中可通过 `npm install vue-router`(或搭配国内镜像源及 `vue-router@4` CDN 产物)安装路由库。

基础集成包含四个必要步骤:一是在 `src/router/index.js` 中用 `createRouter` 与 `createWebHistory()` 创建路由表;二是在 `main.js` 中通过 `createApp(App).use(router).mount('#app')` 挂载路由插件;三是在模板放置 `<router-view>` 出口;四是用 `<router-link to="/about">` 声明跳转链接。

进阶场景常用五项配置:动态路由 `/user/:id`(访问 `/user/10` 时 `$route.params.id === '10'`);基于动态 `import()` 的组件懒加载;借助 `router.beforeEach` 的全局鉴权导航守卫;`redirect` 路径重定向(如 `/old` 指向 `/`);以及放在路由表末尾的 `/:pathMatch(.*)*` 404 兜底路由。本站实测 `/user/10?tab=posts#bio` 精确解析 `params.id='10'`、`query.tab='posts'`、`hash='#bio'`,`/old` 重定向至 `Home`,未知路径 `/nonexistent/page` 渲染 `404 Not Found`。

简单实例、完整项目三文件与 <router-link> 属性

`<router-link>` 渲染为带正确 `href` 的 `<a>` 标签并拦截默认刷新,点击激活后会自动附加 `router-link-active` 与 `router-link-exact-active` 类名;`<router-view>` 则作为路由出口可放置在任意布局位置。无论是 `createWebHashHistory()`(Hash 模式,URL 带 `#`)还是 `createWebHistory()`(History 模式),都能在不重载页面的前提下切换视图。实测 SPA 多次跳转后 `window.__bootCount` 始终为 `1`,History `push` 使历史栈增 1、`replace` 保持历史栈长度不变,Hash 模式精确更新 `location.hash` 为 `#/hash-about`。

在完整工程中,`main.js` 负责 `app.use(router)` 挂载,`router/index.js` 集中声明 `Home`、`About` 与末尾 `NotFound` 路由记录,`App.vue` 组合 `<nav>` 中的 `<router-link>`(支持自定义 `active-class="active-link"`)与 `<main>` 中的 `<router-view>`:点击 Home 显示 `Home Page`,点击 About 显示 `About Us`,点击无效路径显示 `404 Not Found`。

`<router-link>` 常用属性中:`to` 支持路径字符串或描述对象(含 `path`、`name`、`params`、`query`);`replace` 改为调用 `router.replace()` 不新增历史记录;`active-class` 与 `exact-active-class` 分别自定义包含匹配与精确匹配时的激活类名。需特别注意:历史版本(Vue Router 3)的 `append`、`tag` 与 `event` 属性已在 Vue Router 4 中移除,若需自定义渲染标签或触发事件,应统一改用 `custom` 属性配合 `v-slot="{ href, navigate, isActive }"` 作用域插槽实现。

Vue Router v4 核心 API 与导航守卫全览

Vue Router v4 API 分为配置、历史模式、路由记录与实例导航四大组:`createRouter` 接收 `history`、`routes`、`scrollBehavior`、`strict`、`linkActiveClass`、`linkExactActiveClass`、`parseQuery`/`stringifyQuery`;历史工厂提供 `createWebHistory()`、`createWebHashHistory()` 与适用于 SSR 的 `createMemoryHistory()`;路由记录支持 `path`、`name`、`component`/`components`、`redirect`、`children`、`props`、`meta`、`alias` 与 `beforeEnter`;实例方法提供 `push`、`replace`、`back`、`forward`、`go` 以及动态路由增删查 `addRoute`/`removeRoute`/`getRoutes`/`hasRoute`。

导航守卫按全局(`beforeEach`、`beforeResolve`、`afterEach`)、路由独享(`beforeEnter`)与组件内(`beforeRouteEnter`、`beforeRouteUpdate`、`beforeRouteLeave`)分层执行;在 `<script setup>` 组合式 API 中通过 `useRouter()` 与 `useRoute()` 获取路由实例与当前路由对象(含 `params`、`query`、`hash`、`fullPath`、`name`、`path`、`meta`、`matched`),且 `router.push` 返回 Promise 支持 `await`。本站离线回环 Chromium 实测验证未登录访问带 `meta.auth` 的 `/home/dashboard` 被 `beforeEach` 重定向至 `Login`,参数切换触发 `beforeRouteUpdate`,动态 `addRoute('Post')`/`removeRoute('Post')` 实时生效。

Vue Router 核心组成部分

组成部分职责描述选项式 API组合式 API
router 实例全局路由控制器,负责编程式跳转、动态增删路由与注册守卫this.$routeruseRouter()
route 对象只读的当前激活路由状态,包含 path、params、query、meta 等信息this.$routeuseRoute()
<router-link>声明式导航链接组件,渲染为 <a> 并拦截默认整页刷新--
<router-view>路由视图出口,按匹配层级渲染对应组件--

createRouter 配置项

配置项用途说明典型写法
history指定路由历史模式实现(History / Hash / Memory)createWebHistory()
routes路由记录定义数组[{ path: '/', component: Home }]
scrollBehavior控制路由切换后的页面滚动位置() => ({ top: 0 })
strict是否严格区分路径末尾斜杠strict: true
linkActiveClass全局覆盖链接激活时的 CSS 类名'active'
linkExactActiveClass全局覆盖链接精确匹配时的 CSS 类名'exact-active'
parseQuery自定义 URL 查询字符串解析器(q) => ({ ... })
stringifyQuery自定义查询对象序列化函数(obj) => 'a=1'

History 模式工厂函数

工厂 API适用场景调用示例
createWebHistory()基于 HTML5 History API 的干净路径模式(需服务端回退配置)createWebHistory()
createWebHashHistory()URL 带 # 的 Hash 模式,无需服务端特殊配置createWebHashHistory()
createMemoryHistory()内存历史栈,适用于 SSR 服务端渲染或无浏览器测试环境createMemoryHistory()

RouteRecord 路由记录字段

字段用途说明配置示例
path路由匹配路径模板(支持 :id 动态段与正则)'/user/:id'
name唯一路由名称,便于命名跳转与动态移除name: 'User'
component默认视图出口渲染的组件(支持懒加载函数)UserView
components多命名视图映射表(配合 <router-view name>){ default: A, left: B }
redirect访问该路径时的重定向目标redirect: '/login'
children嵌套子路由数组,渲染到父组件内层 <router-view>[{ path: 'profile' }]
props将路由 params 解耦传入组件 propsprops: true
meta挂载鉴权、标题等自定义元信息{ auth: true }
alias为同一路由配置额外访问路径别名alias: '/b'
beforeEnter仅在进入该路由时执行的独享守卫beforeEnter: (to, from) => {}

Router 实例导航与动态路由方法

Router 方法功能说明调用示例
router.push(to)编程式跳转并向历史栈压入新记录router.push('/a')
router.replace(to)替换当前历史记录,不新增栈项router.replace('/a')
router.back()在历史栈中后退一步(等价 go(-1))router.back()
router.forward()在历史栈中前进一步(等价 go(1))router.forward()
router.go(n)按相对偏移量 n 跳转历史记录router.go(-1)
router.addRoute(route)运行时动态新增一条路由记录router.addRoute({ name: 'Post', ... })
router.removeRoute(name)按路由名称动态移除路由记录router.removeRoute('Post')
router.getRoutes()返回当前已注册的所有标准化路由记录数组router.getRoutes()
router.hasRoute(name)判断指定名称的路由是否已存在router.hasRoute('Post')

Vue Router 导航守卫

守卫名称作用域典型签名
router.beforeEach全局前置守卫,常用于统一鉴权与重定向(to, from) => true | '/login'
router.beforeResolve全局解析守卫,在组件内守卫和异步组件解析后触发(to, from) => {}
router.afterEach全局后置钩子,不能取消导航,适合改标题或埋点(to, from, failure) => {}
beforeEnter路由配置独享前置守卫beforeEnter: (to, from) => {}
beforeRouteEnter组件内进入守卫,此时组件实例尚未创建(无法访问 this)beforeRouteEnter(to, from, next) {}
beforeRouteUpdate同一组件复用但参数变更时触发(如 /user/10 -> /user/42)beforeRouteUpdate(to, from) {}
beforeRouteLeave离开当前路由组件前触发,常用于未保存提示beforeRouteLeave(to, from) {}

<router-link> 核心属性(Vue Router v4)

属性用途说明示例
to目标路由路径字符串或位置描述对象to="/a" 或 :to="{ name: 'User', params: { id: 1 } }"
replace点击时使用 router.replace() 代替 push()<router-link to="/a" replace>
custom关闭默认 <a> 包裹,配合 v-slot 自定义渲染标签与事件<router-link custom v-slot="{ href, navigate }">
active-class覆盖包含匹配激活时的 CSS 类名active-class="active-link"
exact-active-class覆盖精确匹配激活时的 CSS 类名exact-active-class="exact"

<router-view> 核心属性

属性用途说明示例
name指定命名视图出口名称,默认值为 default<router-view name="left">
route高级用法:强制渲染指定的标准化路由位置对象<router-view :route="someRoute">

Route 当前路由对象字段

字段类型含义说明访问示例
paramsobject动态路径参数键值对route.params.id
queryobjectURL 查询字符串解析结果route.query.tab
hashstringURL 中带 # 的锚点片段route.hash
fullPathstring含路径、查询参数与哈希的完整解析路径'/user/10?tab=posts#bio'
namestring | symbol | undefined匹配到的路由记录名称'User'
pathstring当前解码路径(不含 query 与 hash)'/user/10'
metaobject合并后的路由元信息对象route.meta.auth
matchedRouteRecordNormalized[]当前路径匹配到的全层级路由记录数组route.matched

Vue Router 组合式 API

API功能说明调用示例
useRoute()在 setup 中获取响应式当前路由对象const route = useRoute()
useRouter()在 setup 中获取全局路由器实例const router = useRouter()

编程式导航常见写法

使用场景调用示例说明
命名路由跳转router.push({ name: 'User', params: { id: 42 } })不硬编码路径格式,重构路径更安全
带 Query 参数跳转router.push({ path: '/search', query: { q: 'x' } })自动序列化为查询字符串
可等待的 Push/Replaceawait router.push('/about')导航异步完成,可按需捕获取消或失败
URL 对象跳转router.push({ path: '/foo', hash: '#bar' })精细控制 path、query 与 hash 组合

在离线回环 Chromium 中验证 History/Hash 导航、动态参数与 404、嵌套命名视图及导航守卫

python · 阅读源码
"""Offline Playwright Chromium lab for Vue 3 Ch 25: SPA routing (Vue Router v4 semantics)."""
import http.server
import json
import threading
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 v4 Offline Lab</title>
</head>
<body>
  <nav id="nav">
    <a id="link-home" data-to="/" data-active="active-link" href="/">Home</a>
    <a id="link-about" data-to="/about" data-active="active-link" href="/about">About</a>
    <a id="link-404" data-to="/nonexistent" href="/nonexistent">404</a>
  </nav>
  <main id="router-view"></main>
  <aside id="named-left"></aside>
<script>
window.__bootCount = (window.__bootCount || 0) + 1;

function compilePattern(pattern) {
  if (pattern === '/:pathMatch(.*)*') {
    return { regex: /^\/(.*)$/, keys: ['pathMatch'] };
  }
  const keys = [];
  const src = pattern.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {
    keys.push(k);
    return '([^/]+)';
  });
  return { regex: new RegExp('^' + src + '$'), keys };
}

function parseUrl(raw) {
  const u = new URL(raw, window.location.origin);
  const query = {};
  u.searchParams.forEach((v, k) => { query[k] = v; });
  return {
    path: u.pathname,
    query,
    hash: u.hash,
    fullPath: u.pathname + u.search + u.hash
  };
}

function createOfflineRouter(config) {
  let routes = config.routes.slice();
  const beforeEachGuards = [];
  const beforeResolveGuards = [];
  const afterEachHooks = [];
  let currentRoute = { path: '/', params: {}, query: {}, hash: '', fullPath: '/', name: null, meta: {}, matched: [] };

  function matchRoute(rawLocation) {
    let rawUrl;
    if (typeof rawLocation === 'string') {
      rawUrl = rawLocation;
    } else if (rawLocation.name) {
      const rec = findByName(routes, rawLocation.name);
      if (!rec) return null;
      let p = rec.fullPattern;
      for (const [k, v] of Object.entries(rawLocation.params || {})) {
        p = p.replace(':' + k, encodeURIComponent(String(v)));
      }
      const qs = new URLSearchParams(rawLocation.query || {}).toString();
      rawUrl = p + (qs ? '?' + qs : '') + (rawLocation.hash || '');
    } else {
      const qs = new URLSearchParams(rawLocation.query || {}).toString();
      rawUrl = (rawLocation.path || '/') + (qs ? '?' + qs : '') + (rawLocation.hash || '');
    }

    const parsed = parseUrl(rawUrl);
    for (const r of flattenRoutes(routes)) {
      const { regex, keys } = compilePattern(r.fullPattern);
      const m = parsed.path.match(regex);
      if (m) {
        const params = {};
        keys.forEach((k, i) => { params[k] = m[i + 1]; });
        const target = r.record;
        if (target.redirect) {
          return matchRoute(target.redirect);
        }
        return {
          path: parsed.path,
          params,
          query: parsed.query,
          hash: parsed.hash,
          fullPath: parsed.fullPath,
          name: target.name || null,
          meta: Object.assign({}, ...r.chain.map(c => c.meta || {})),
          matched: r.chain
        };
      }
    }
    return null;
  }

  function flattenRoutes(list, prefix = '', chain = []) {
    const out = [];
    for (const r of list) {
      const full = r.path.startsWith('/') ? r.path : (prefix.replace(/\/$/, '') + '/' + r.path);
      const nextChain = chain.concat(r);
      if (r.children && r.children.length) {
        out.push(...flattenRoutes(r.children, full, nextChain));
      } else {
        out.push({ fullPattern: full, record: r, chain: nextChain });
      }
      if (r.alias) {
        out.push({ fullPattern: r.alias, record: r, chain: nextChain });
      }
    }
    return out;
  }

  function findByName(list, name, prefix = '') {
    for (const r of list) {
      const full = r.path.startsWith('/') ? r.path : (prefix.replace(/\/$/, '') + '/' + r.path);
      if (r.name === name) return { record: r, fullPattern: full };
      if (r.children) {
        const sub = findByName(r.children, name, full);
        if (sub) return sub;
      }
    }
    return null;
  }

  async function navigate(toLoc, replace = false) {
    const to = matchRoute(toLoc);
    const from = currentRoute;
    if (!to) return false;

    // Component beforeRouteLeave
    const prevLeaf = from.matched[from.matched.length - 1];
    if (prevLeaf && prevLeaf.beforeRouteLeave) {
      const r = await prevLeaf.beforeRouteLeave(to, from);
      if (r === false) return false;
    }

    // Global beforeEach
    for (const g of beforeEachGuards) {
      const res = await g(to, from);
      if (res === false) return false;
      if (typeof res === 'string' || (res && typeof res === 'object')) {
        return navigate(res, replace);
      }
    }

    // Route beforeEnter
    const leaf = to.matched[to.matched.length - 1];
    if (leaf && leaf.beforeEnter) {
      const res = await leaf.beforeEnter(to, from);
      if (res === false) return false;
      if (typeof res === 'string') return navigate(res, replace);
    }

    // Component beforeRouteUpdate when same component reused
    if (prevLeaf && leaf && prevLeaf.name && prevLeaf.name === leaf.name && leaf.beforeRouteUpdate) {
      await leaf.beforeRouteUpdate(to, from);
    }

    // Global beforeResolve
    for (const g of beforeResolveGuards) {
      await g(to, from);
    }

    currentRoute = to;
    if (config.mode === 'hash') {
      window.location.hash = '#' + to.fullPath;
    } else if (replace) {
      window.history.replaceState({}, '', to.fullPath);
    } else {
      window.history.pushState({}, '', to.fullPath);
    }
    renderView(to);
    for (const h of afterEachHooks) h(to, from);
    return true;
  }

  let layoutShell = null;
  function renderView(route) {
    const rootView = document.getElementById('router-view');
    const leftView = document.getElementById('named-left');
    leftView.textContent = '';

    if (route.matched.length === 2 && route.matched[0].name === 'Layout') {
      if (!layoutShell || !rootView.contains(layoutShell)) {
        layoutShell = document.createElement('section');
        layoutShell.id = 'layout-shell';
        layoutShell.innerHTML = '<header>Header</header><div id="child-view"></div><footer>Footer</footer>';
        rootView.innerHTML = '';
        rootView.appendChild(layoutShell);
      }
      const leaf = route.matched[1];
      document.getElementById('child-view').textContent = leaf.render(route);
      if (leaf.components && leaf.components.left) {
        leftView.textContent = leaf.components.left(route);
      }
    } else {
      layoutShell = null;
      const leaf = route.matched[0];
      rootView.textContent = leaf.render ? leaf.render(route) : '';
    }

    // Update <router-link> active classes
    document.querySelectorAll('#nav a').forEach(a => {
      const to = a.dataset.to;
      const customActive = a.dataset.active || 'router-link-active';
      a.className = '';
      if (route.path === to) {
        a.classList.add(customActive, 'router-link-exact-active');
      } else if (to !== '/' && route.path.startsWith(to)) {
        a.classList.add(customActive);
      }
    });
  }

  return {
    push: (to) => navigate(to, false),
    replace: (to) => navigate(to, true),
    beforeEach: (fn) => beforeEachGuards.push(fn),
    beforeResolve: (fn) => beforeResolveGuards.push(fn),
    afterEach: (fn) => afterEachHooks.push(fn),
    addRoute: (r) => routes.splice(routes.length - 1, 0, r),
    removeRoute: (name) => { routes = routes.filter(r => r.name !== name); },
    hasRoute: (name) => Boolean(findByName(routes, name)),
    getRoutes: () => flattenRoutes(routes).map(x => x.record.name || x.fullPattern),
    useRoute: () => currentRoute
  };
}

window.runRouterTests = async function () {
  const guardTrace = [];
  let isAuthed = false;

  const router = createOfflineRouter({
    mode: 'history',
    routes: [
      { path: '/', name: 'Home', render: () => 'Home Page' },
      { path: '/about', name: 'About', render: () => 'About Us' },
      { path: '/login', name: 'Login', render: () => 'Login Page' },
      { path: '/old', redirect: '/' },
      {
        path: '/user/:id',
        name: 'User',
        render: (r) => `User:${r.params.id}|tab=${r.query.tab || ''}`,
        beforeRouteUpdate(to, from) { guardTrace.push(`update:${from.params.id}->${to.params.id}`); }
      },
      {
        path: '/home',
        name: 'Layout',
        children: [
          {
            path: 'dashboard',
            name: 'Dashboard',
            meta: { auth: true },
            beforeEnter() { guardTrace.push('beforeEnter:Dashboard'); },
            render: () => 'Dashboard Child',
            components: { left: () => 'Sidebar-Dashboard' }
          },
          {
            path: 'setting',
            name: 'Setting',
            render: () => 'Setting Child',
            components: { left: () => 'Sidebar-Setting' }
          }
        ]
      },
      { path: '/:pathMatch(.*)*', name: 'NotFound', render: () => '404 Not Found' }
    ]
  });

  router.beforeEach((to) => {
    if (to.meta.auth && !isAuthed) {
      guardTrace.push('redirect-to-login');
      return '/login';
    }
  });
  router.beforeResolve((to) => {
    if (to.name === 'Dashboard') guardTrace.push('beforeResolve:Dashboard');
  });
  router.afterEach((to) => {
    if (to.name === 'Dashboard') guardTrace.push('afterEach:Dashboard');
  });

  // Case 1: SPA history push/replace + active classes + hash mode
  await router.push('/');
  const homeView = document.getElementById('router-view').textContent;
  const homeCls = document.getElementById('link-home').className;
  const lenBeforePush = window.history.length;
  await router.push('/about');
  const aboutPath = window.location.pathname;
  const aboutCls = document.getElementById('link-about').className;
  const lenAfterPush = window.history.length;
  await router.replace('/');
  const lenAfterReplace = window.history.length;
  const hashRouter = createOfflineRouter({
    mode: 'hash',
    routes: [{ path: '/hash-about', name: 'HashAbout', render: () => 'Hash About' }]
  });
  await hashRouter.push('/hash-about');
  const hashVal = window.location.hash;

  // Case 2: Dynamic params, query, hash, named route, redirect, 404
  await router.push('/user/10?tab=posts#bio');
  const rUser = router.useRoute();
  const userSnap = {
    params_id: rUser.params.id,
    query_tab: rUser.query.tab,
    hash: rUser.hash,
    fullPath: rUser.fullPath,
    view: document.getElementById('router-view').textContent
  };
  await router.push({ name: 'User', params: { id: 42 }, query: { tab: 'likes' } });
  const namedPath = router.useRoute().fullPath;
  await router.push('/old');
  const redirectTarget = router.useRoute().name;
  await router.push('/nonexistent/page');
  const notFoundView = document.getElementById('router-view').textContent;

  // Case 3: Nested routes + persistent layout shell + named view
  isAuthed = true;
  await router.push('/home/dashboard');
  const shellRef1 = document.getElementById('layout-shell');
  const dashMatched = router.useRoute().matched.length;
  const dashChild = document.getElementById('child-view').textContent;
  const dashLeft = document.getElementById('named-left').textContent;
  await router.push('/home/setting');
  const shellRef2 = document.getElementById('layout-shell');
  const settingChild = document.getElementById('child-view').textContent;
  const settingLeft = document.getElementById('named-left').textContent;

  // Case 4: Guards + dynamic addRoute/removeRoute
  isAuthed = false;
  await router.push('/home/dashboard');
  const unauthedRedirect = router.useRoute().name;
  router.addRoute({ path: '/post', name: 'Post', render: () => 'Dynamic Post' });
  const hasPostBefore = router.hasRoute('Post');
  await router.push('/post');
  const postView = document.getElementById('router-view').textContent;
  router.removeRoute('Post');
  const hasPostAfter = router.hasRoute('Post');

  return {
    case1: {
      boot_count: window.__bootCount,
      home_view: homeView,
      home_class: homeCls,
      about_path: aboutPath,
      about_class: aboutCls,
      push_added_entry: lenAfterPush === lenBeforePush + 1,
      replace_kept_length: lenAfterReplace === lenAfterPush,
      hash_url: hashVal
    },
    case2: {
      user_snapshot: userSnap,
      named_push_fullPath: namedPath,
      redirect_target: redirectTarget,
      not_found_view: notFoundView
    },
    case3: {
      matched_depth: dashMatched,
      dashboard_child: dashChild,
      dashboard_left: dashLeft,
      shell_preserved: shellRef1 === shellRef2,
      setting_child: settingChild,
      setting_left: settingLeft
    },
    case4: {
      unauthed_redirect: unauthedRedirect,
      guard_trace: guardTrace,
      has_post_before: hasPostBefore,
      post_view: postView,
      has_post_after: hasPostAfter
    }
  };
};
</script>
</body>
</html>
"""


class Handler(http.server.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():
    srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    port = srv.server_address[1]
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            page = browser.new_page()
            page.goto(f"http://127.0.0.1:{port}/")
            out = page.evaluate("window.runRouterTests()")
            browser.close()
    finally:
        srv.shutdown()
        srv.server_close()

    expected = {
        "hash_and_history_spa_navigation": {
            "boot_count": 1,
            "home_view": "Home Page",
            "home_class": "active-link router-link-exact-active",
            "about_path": "/about",
            "about_class": "active-link router-link-exact-active",
            "push_added_entry": True,
            "replace_kept_length": True,
            "hash_url": "#/hash-about",
        },
        "dynamic_params_query_hash_and_404": {
            "user_snapshot": {
                "params_id": "10",
                "query_tab": "posts",
                "hash": "#bio",
                "fullPath": "/user/10?tab=posts#bio",
                "view": "User:10|tab=posts",
            },
            "named_push_fullPath": "/user/42?tab=likes",
            "redirect_target": "Home",
            "not_found_view": "404 Not Found",
        },
        "nested_routes_and_named_views": {
            "matched_depth": 2,
            "dashboard_child": "Dashboard Child",
            "dashboard_left": "Sidebar-Dashboard",
            "shell_preserved": True,
            "setting_child": "Setting Child",
            "setting_left": "Sidebar-Setting",
        },
        "navigation_guards_and_dynamic_routes": {
            "unauthed_redirect": "Login",
            "guard_trace": [
                "update:10->42",
                "beforeEnter:Dashboard",
                "beforeResolve:Dashboard",
                "afterEach:Dashboard",
                "redirect-to-login",
            ],
            "has_post_before": True,
            "post_view": "Dynamic Post",
            "has_post_after": False,
        },
    }
    mapping = [
        ("hash_and_history_spa_navigation", out["case1"]),
        ("dynamic_params_query_hash_and_404", out["case2"]),
        ("nested_routes_and_named_views", out["case3"]),
        ("navigation_guards_and_dynamic_routes", out["case4"]),
    ]
    cases = [
        {"name": name, "expected": expected[name], "actual": actual, "passed": actual == expected[name]}
        for name, actual in mapping
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对无刷新 SPA 跳转、push/replace 历史栈差异、/user/:id 参数与 query/hash 解析、Layout 持久外框与命名视图、beforeEach 鉴权重定向及 addRoute/removeRoute。
在离线回环 Chromium 中验证 History/Hash 导航、动态参数与 404、嵌套命名视图及导航守卫

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:b9093a54ed9d6135b62d87d52e81f9edffc19f806afbb52c93428041bf657c09

下载本站示例源码

本地运行

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

下载Vue3 路由实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:93ba5b0a88ee0b9b039d8af8d1438b9e4f935685c3f0d68649c3b34700d51517

常见错误与边界

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

练习与解答

在 Vue Router v4 中,router.push() 与 router.replace() 对浏览器历史栈有何差异?为什么要移除 tag/event 属性改用 custom + v-slot?

展开参考解答

router.push() 会在历史栈新增一条记录(可后退),router.replace() 替换当前记录;Vue Router 4 用 custom 搭配 v-slot 统一接管渲染标签、激活类与触发事件,减少了 prop 膨胀并增强了可访问性与灵活性。

规范与官方依据