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

离线实测 Proxy 响应式、useCounter 组合式函数、内置组件、生命周期钩子与 TS/Tree-shaking 解析

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-introduction.py
explore-introduction.py333 行
"""Offline Playwright Chromium verification for Vue 3 Ch02 (introduction)."""
import json
import re
from playwright.sync_api import sync_playwright


def launch_browser(p):
    for kwargs in (
        dict(headless=True),
        dict(headless=True, channel="chrome"),
        dict(headless=True, channel="msedge"),
    ):
        try:
            return p.chromium.launch(**kwargs)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


def case_proxy_vs_defineproperty_reactivity(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head><body>
<script>
  const dpLogs = [];
  const vue2Obj = {};
  let _name = "Vue2";
  Object.defineProperty(vue2Obj, "name", {
    get() { return _name; },
    set(v) { _name = v; dpLogs.push(`name=${v}`); }
  });
  vue2Obj.name = "Vue2-updated";
  vue2Obj.email = "new@example.com";
  const dpArr = ["vue", "ts"];
  dpArr[0] = "vue2";

  const proxyLogs = [];
  function reactive(obj) {
    return new Proxy(obj, {
      get(target, key, receiver) {
        const res = Reflect.get(target, key, receiver);
        return (res && typeof res === "object") ? reactive(res) : res;
      },
      set(target, key, value, receiver) {
        const prev = target[key];
        const ok = Reflect.set(target, key, value, receiver);
        if (prev !== value) proxyLogs.push(`${String(key)}=${value}`);
        return ok;
      }
    });
  }
  function ref(init) {
    const watchers = [];
    let _val = init;
    return {
      get value() { return _val; },
      set value(v) {
        const oldVal = _val;
        _val = v;
        watchers.forEach((cb) => cb(v, oldVal));
      },
      _watch(cb) { watchers.push(cb); }
    };
  }
  const user = reactive({ name: "BlueSky", age: 18, skills: ["vue", "typescript"] });
  user.email = "dev@example.com";
  user.skills[0] = "vue3";

  const count = ref(0);
  const watchEvents = [];
  count._watch((newVal, oldVal) => watchEvents.push(`${oldVal}->${newVal}`));
  count.value = 10;

  window.__res = {
    definePropertyTracked: dpLogs,
    definePropertyMissedEmail: !dpLogs.some((s) => s.startsWith("email=")),
    proxyTracked: proxyLogs,
    userEmail: user.email,
    firstSkill: user.skills[0],
    watchEvents
  };
</script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__res")
    expected = {
        "definePropertyTracked": ["name=Vue2-updated"],
        "definePropertyMissedEmail": True,
        "proxyTracked": ["email=dev@example.com", "0=vue3"],
        "userEmail": "dev@example.com",
        "firstSkill": "vue3",
        "watchEvents": ["0->10"],
    }
    return dict(name="proxy_vs_defineproperty_reactivity", expected=expected, actual=actual, passed=(actual == expected))


def case_composition_api_and_composable(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head><body>
  <div id="app1"></div>
  <div id="app2"></div>
  <script>
    function ref(init) {
      const subs = new Set();
      let _v = init;
      return {
        get value() { return _v; },
        set value(v) { _v = v; subs.forEach((f) => f()); },
        _sub(fn) { subs.add(fn); }
      };
    }
    function useCounter(initialValue = 0) {
      const count = ref(initialValue);
      const doubled = () => count.value * 2;
      const increment = () => { count.value++; };
      const decrement = () => { count.value--; };
      const reset = () => { count.value = initialValue; };
      return { count, doubled, increment, decrement, reset };
    }
    function createApp(initial) {
      const api = useCounter(initial);
      return {
        api,
        mount(sel) {
          const el = document.querySelector(sel);
          const render = () => { el.textContent = `count=${api.count.value},doubled=${api.doubled()}`; };
          api.count._sub(render);
          render();
          return api;
        }
      };
    }
    const vm1 = createApp(10).mount("#app1");
    const vm2 = createApp(0).mount("#app2");
    vm1.increment();
    vm1.increment();
    const afterInc = document.getElementById("app1").textContent;
    vm1.decrement();
    const afterDec = document.getElementById("app1").textContent;
    vm1.reset();
    const afterReset = document.getElementById("app1").textContent;
    vm2.increment();
    window.__res = {
      afterInc,
      afterDec,
      afterReset,
      app2Isolated: document.getElementById("app2").textContent
    };
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__res")
    expected = {
        "afterInc": "count=12,doubled=24",
        "afterDec": "count=11,doubled=22",
        "afterReset": "count=10,doubled=20",
        "app2Isolated": "count=1,doubled=2",
    }
    return dict(name="composition_api_and_composable", expected=expected, actual=actual, passed=(actual == expected))


def case_fragment_teleport_suspense_dom(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head><body>
  <section id="frag-host"></section>
  <div id="clipped-parent" style="overflow:hidden; position:relative; z-index:1;">
    <button id="open-modal">打开弹窗</button>
  </div>
  <div id="suspense-host"></div>
  <script>
    const frag = document.createDocumentFragment();
    const h = document.createElement("header"); h.textContent = "头部节点";
    const m = document.createElement("main"); m.textContent = "主体节点";
    frag.append(h, m);
    document.getElementById("frag-host").appendChild(frag);

    document.getElementById("open-modal").addEventListener("click", () => {
      const modal = document.createElement("div");
      modal.id = "teleported-modal";
      modal.textContent = "全局弹窗";
      document.body.appendChild(modal);
    });

    const sHost = document.getElementById("suspense-host");
    sHost.innerHTML = '<div class="loading">加载中...</div>';
    window.__fallbackText = sHost.textContent.trim();
    window.__resolveAsync = () => new Promise((resolve) => {
      setTimeout(() => {
        sHost.innerHTML = '<div class="profile">异步用户资料已就绪</div>';
        resolve(sHost.textContent.trim());
      }, 20);
    });
  </script>
</body></html>"""
    page.set_content(html)
    page.click("#open-modal")
    resolved_text = page.evaluate("window.__resolveAsync()")
    actual = page.evaluate(
        """() => ({
            fragmentChildren: Array.from(document.getElementById('frag-host').children).map(e => e.tagName),
            modalParentTag: document.getElementById('teleported-modal').parentElement.tagName,
            insideClippedParent: document.getElementById('clipped-parent').contains(document.getElementById('teleported-modal')),
            fallbackText: window.__fallbackText
        })"""
    )
    actual["resolvedText"] = resolved_text
    expected = {
        "fragmentChildren": ["HEADER", "MAIN"],
        "modalParentTag": "BODY",
        "insideClippedParent": False,
        "fallbackText": "加载中...",
        "resolvedText": "异步用户资料已就绪",
    }
    return dict(name="fragment_teleport_suspense_dom", expected=expected, actual=actual, passed=(actual == expected))


def case_lifecycle_hooks_sequence(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head><body>
  <div id="lc-root"></div>
  <script>
  (() => {
    const log = [];
    let count = 0;
    let timer = null;
    const root = document.getElementById("lc-root");
    function mountComponent() {
      log.push("setup");
      log.push("onBeforeMount");
      root.textContent = `已运行:${count} 秒`;
      log.push("onMounted");
      timer = setInterval(() => { count++; }, 15);
    }
    function updateComponent(nextCount) {
      log.push("onBeforeUpdate");
      count = nextCount;
      root.textContent = `已运行:${count} 秒`;
      log.push("onUpdated");
    }
    function unmountComponent() {
      log.push("onBeforeUnmount");
      clearInterval(timer);
      timer = null;
      root.textContent = "";
      log.push("onUnmounted");
    }
    mountComponent();
    updateComponent(1);
    unmountComponent();
    const countAfterUnmount = count;
    window.__checkAfterWait = () => new Promise((resolve) => {
      setTimeout(() => resolve({ log, countStableAfterUnmount: count === countAfterUnmount, cleared: timer === null }), 40);
    });
  })();
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("window.__checkAfterWait()")
    expected = {
        "log": [
            "setup",
            "onBeforeMount",
            "onMounted",
            "onBeforeUpdate",
            "onUpdated",
            "onBeforeUnmount",
            "onUnmounted",
        ],
        "countStableAfterUnmount": True,
        "cleared": True,
    }
    return dict(name="lifecycle_hooks_sequence", expected=expected, actual=actual, passed=(actual == expected))


def case_ts_sfc_and_treeshaking_analysis():
    all_vue_exports = [
        "ref", "reactive", "computed", "watch", "watchEffect",
        "nextTick", "onMounted", "onUnmounted", "provide", "inject",
    ]
    import_stmt = "import { ref, computed, watch, nextTick, onMounted } from 'vue'"
    m = re.search(r"import\s*\{([^}]+)\}\s*from\s*'vue'", import_stmt)
    imported = [tok.strip() for tok in m.group(1).split(",") if tok.strip()]
    shaken = [name for name in all_vue_exports if name not in imported]

    ts_sfc = """<script setup lang="ts">
import { ref, computed } from 'vue'
interface User { id: number; name: string; email?: string }
const user = ref<User>({ id: 1, name: 'BlueSky' })
const props = defineProps<{ title: string; count?: number }>()
const emit = defineEmits<{ (e: 'update', value: number): void; (e: 'close'): void }>()
const displayName = computed(() => user.value.name.toUpperCase())
</script>"""
    lang = re.search(r'<script\s+setup\s+lang="([^"]+)">', ts_sfc).group(1)
    iface = re.search(r"interface\s+(\w+)", ts_sfc).group(1)
    has_props_macro = "defineProps<" in ts_sfc
    has_emits_macro = "defineEmits<" in ts_sfc

    actual = {
        "retained_count": len(imported),
        "shaken_count": len(shaken),
        "script_lang": lang,
        "interface_name": iface,
        "typed_macros": [has_props_macro, has_emits_macro],
    }
    expected = {
        "retained_count": 5,
        "shaken_count": 5,
        "script_lang": "ts",
        "interface_name": "User",
        "typed_macros": [True, True],
    }
    return dict(name="ts_sfc_and_treeshaking_analysis", expected=expected, actual=actual, passed=(actual == expected))


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            cases = [
                case_proxy_vs_defineproperty_reactivity(page),
                case_composition_api_and_composable(page),
                case_fragment_teleport_suspense_dom(page),
                case_lifecycle_hooks_sequence(page),
                case_ts_sfc_and_treeshaking_analysis(),
            ]
        finally:
            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/vue3-introduction-lab/explore-introduction.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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