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

离线 Chromium 验证 SPA Hash 路由与 <router-link> 属性

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-vue-routing.py
explore-vue-routing.py232 行
"""Offline Chromium runtime verification for Vue 2 Chapter 16: vue-routing."""
import json
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")


def make_case(name, expected, actual):
    return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()

        # Case 1: hash SPA router with router-link, router-view, and active classes
        page.set_content("""
        <!doctype html>
        <html><body>
          <div id="app">
            <h1>Hello App!</h1>
            <p>
              <a id="link-foo" href="#/foo" data-to="/foo">Go to Foo</a>
              <a id="link-bar" href="#/bar" data-to="/bar">Go to Bar</a>
            </p>
            <div id="router-view"></div>
          </div>
          <script>
            const routes = { '/foo': '<div>foo</div>', '/bar': '<div>bar</div>' };
            function renderRoute(explicitPath) {
              const path = explicitPath || (location.hash || '#/').slice(1);
              document.getElementById('router-view').innerHTML = routes[path] || '';
              document.querySelectorAll('a[data-to]').forEach(a => {
                const target = a.dataset.to;
                a.classList.remove('router-link-active', 'router-link-exact-active');
                if (path === target) {
                  a.classList.add('router-link-exact-active', 'router-link-active');
                }
              });
            }
            document.querySelectorAll('a[data-to]').forEach(a => {
              a.addEventListener('click', (e) => {
                e.preventDefault();
                location.hash = '#' + a.dataset.to;
                renderRoute(a.dataset.to);
              });
            });
            window.addEventListener('hashchange', () => renderRoute());
            renderRoute();
          </script>
        </body></html>
        """)
        page.click("#link-foo")
        foo_view = page.locator("#router-view").inner_text()
        foo_cls = page.locator("#link-foo").get_attribute("class") or ""
        page.click("#link-bar")
        bar_view = page.locator("#router-view").inner_text()
        bar_cls = page.locator("#link-bar").get_attribute("class") or ""
        foo_cls_after = page.locator("#link-foo").get_attribute("class") or ""
        actual1 = {
            "fooView": foo_view,
            "fooClasses": sorted(foo_cls.split()),
            "barView": bar_view,
            "barClasses": sorted(bar_cls.split()),
            "fooInactiveAfter": foo_cls_after.strip() == "",
        }
        expected1 = {
            "fooView": "foo",
            "fooClasses": ["router-link-active", "router-link-exact-active"],
            "barView": "bar",
            "barClasses": ["router-link-active", "router-link-exact-active"],
            "fooInactiveAfter": True,
        }
        cases.append(make_case("hash_spa_router_link_view", expected1, actual1))

        # Case 2: router-link `to` variants, `replace`, and `append` path resolution
        page.set_content("<!doctype html><html><body></body></html>")
        actual2 = page.evaluate("""() => {
          const namedRoutes = { user: '/user/:userId' };
          function resolveTo(to, currentPath = '/', append = false) {
            if (typeof to === 'string') {
              if (append && !to.startsWith('/')) {
                const base = currentPath.endsWith('/') ? currentPath : currentPath + '/';
                return base + to;
              }
              return to.startsWith('/') ? to : '/' + to;
            }
            let p = to.path || '';
            if (to.name && namedRoutes[to.name]) {
              p = namedRoutes[to.name].replace(/:([A-Za-z0-9_]+)/g, (_, k) => String(to.params[k]));
            } else if (append && !p.startsWith('/')) {
              const base = currentPath.endsWith('/') ? currentPath : currentPath + '/';
              p = base + p;
            }
            if (to.query) {
              const qs = new URLSearchParams(to.query).toString();
              if (qs) p += '?' + qs;
            }
            return p;
          }
          const stack = ['/'];
          function push(path) { stack.push(path); }
          function replace(path) { stack[stack.length - 1] = path; }
          push('/home');
          const lenAfterPush = stack.length;
          replace('/abc');
          const lenAfterReplace = stack.length;
          return {
            strTo: resolveTo('home'),
            namedParams: resolveTo({ name: 'user', params: { userId: 123 } }),
            withQuery: resolveTo({ path: '/register', query: { plan: 'private' } }),
            withoutAppend: resolveTo('b', '/a', false),
            withAppend: resolveTo('b', '/a', true),
            lenAfterPush,
            lenAfterReplace,
            topAfterReplace: stack[stack.length - 1],
          };
        }""")
        expected2 = {
            "strTo": "/home",
            "namedParams": "/user/123",
            "withQuery": "/register?plan=private",
            "withoutAppend": "/b",
            "withAppend": "/a/b",
            "lenAfterPush": 2,
            "lenAfterReplace": 2,
            "topAfterReplace": "/abc",
        }
        cases.append(make_case("router_link_to_and_replace_append", expected2, actual2))

        # Case 3: tag, active-class, exact-active-class, and event="mouseover"
        page.set_content("""
        <!doctype html>
        <html><head><style>._active { background-color: rgb(255, 0, 0); }</style></head>
        <body>
          <ul>
            <li id="li-route1" data-to="/route1">Router Link 1</li>
          </ul>
          <span id="span-route2" data-to="/route2">Router Link 2</span>
          <div id="view"></div>
          <script>
            let cur = '';
            function nav(path) {
              cur = path;
              document.getElementById('view').textContent = 'View:' + cur;
              const l1 = document.getElementById('li-route1');
              l1.className = (cur === '/route1') ? '_active _exact' : '';
            }
            document.getElementById('li-route1').addEventListener('mouseover', () => nav('/route1'));
            document.getElementById('span-route2').addEventListener('click', () => nav('/route2'));
          </script>
        </body></html>
        """)
        page.hover("#li-route1")
        hover_view = page.locator("#view").inner_text()
        hover_bg = page.evaluate("getComputedStyle(document.getElementById('li-route1')).backgroundColor")
        hover_cls = page.locator("#li-route1").get_attribute("class")
        page.click("#span-route2")
        click_view = page.locator("#view").inner_text()
        actual3 = {
            "liTag": page.evaluate("document.getElementById('li-route1').tagName"),
            "spanTag": page.evaluate("document.getElementById('span-route2').tagName"),
            "hoverView": hover_view,
            "hoverBg": hover_bg,
            "hoverClass": hover_cls,
            "clickView": click_view,
        }
        expected3 = {
            "liTag": "LI",
            "spanTag": "SPAN",
            "hoverView": "View:/route1",
            "hoverBg": "rgb(255, 0, 0)",
            "hoverClass": "_active _exact",
            "clickView": "View:/route2",
        }
        cases.append(make_case("router_link_tag_active_class_event", expected3, actual3))

        # Case 4: simple Home / About / 404 routing app (offline equivalent of simple routing example)
        page.goto("about:blank")
        page.set_content("""
        <!doctype html>
        <html><body>
          <ul>
            <li>
              <a id="nav-home" href="#/" data-path="/">Home</a>
              <a id="nav-about" href="#/about" data-path="/about">About</a>
            </li>
          </ul>
          <p id="page-body"></p>
          <script>
            const pages = { '/': 'Welcome home', '/about': 'About page' };
            function sync(explicitPath) {
              const p = explicitPath !== undefined ? explicitPath : (location.hash || '#/').slice(1);
              document.getElementById('page-body').textContent = pages[p] || 'Page not found';
            }
            document.querySelectorAll('a[data-path]').forEach(a => {
              a.addEventListener('click', (e) => {
                e.preventDefault();
                location.hash = '#' + a.dataset.path;
                sync(a.dataset.path);
              });
            });
            window.__navTo = (p) => { location.hash = '#' + p; sync(p); };
            window.addEventListener('hashchange', () => sync());
            sync('/');
          </script>
        </body></html>
        """)
        home_txt = page.locator("#page-body").inner_text()
        page.click("#nav-about")
        about_txt = page.locator("#page-body").inner_text()
        page.evaluate("window.__navTo('/unknown')")
        not_found_txt = page.locator("#page-body").inner_text()
        actual4 = {"home": home_txt, "about": about_txt, "unknown": not_found_txt}
        expected4 = {"home": "Welcome home", "about": "About page", "unknown": "Page not found"}
        cases.append(make_case("simple_routing_home_about_404", expected4, actual4))

        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

下载课程关联工程包:Vue.js

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

下载课程关联工程包:Vue.js

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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