蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-routing.py
explore-routing.py481 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/vue3-routing-lab/explore-routing.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-routing.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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