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

在离线 Chromium 中验证 ES Proxy 响应式核心、生命周期、模板引用与 flush:'post'

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-composition-api.py
explore-composition-api.py437 行
"""Offline Playwright Chromium lab for Vue 3 Ch 28: Composition API reactivity & lifecycle."""
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")


HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 Composition API Lab</title>
</head>
<body>
  <div id="counter-text"></div>
  <button id="counter-btn">+1</button>
  <div id="tpl-root">This is a root element</div>
  <div id="list-box"></div>
<script>
// Minimal offline Vue 3 Composition API reactivity core (ES Proxy)
let activeEffect = null;
let activeScope = null;
const targetMap = new WeakMap();
const RAW_SYM = Symbol('raw');
const REACTIVE_SYM = Symbol('isReactive');
const READONLY_SYM = Symbol('isReadonly');
const SKIP_SYM = Symbol('markRaw');

function track(target, key) {
  if (!activeEffect) return;
  let depsMap = targetMap.get(target);
  if (!depsMap) targetMap.set(target, (depsMap = new Map()));
  let dep = depsMap.get(key);
  if (!dep) depsMap.set(key, (dep = new Set()));
  dep.add(activeEffect);
  activeEffect.deps.add(dep);
}

function trigger(target, key) {
  const depsMap = targetMap.get(target);
  if (!depsMap) return;
  const dep = depsMap.get(key);
  if (!dep) return;
  [...dep].forEach(eff => {
    if (eff.scheduler) eff.scheduler();
    else eff.run();
  });
}

function reactive(obj) {
  if (!obj || typeof obj !== 'object' || obj[SKIP_SYM]) return obj;
  return new Proxy(obj, {
    get(target, key, receiver) {
      if (key === RAW_SYM) return target;
      if (key === REACTIVE_SYM) return true;
      const res = Reflect.get(target, key, receiver);
      track(target, key);
      return res && typeof res === 'object' ? reactive(res) : res;
    },
    set(target, key, value, receiver) {
      const oldVal = target[key];
      const ok = Reflect.set(target, key, value, receiver);
      if (oldVal !== value) trigger(target, key);
      return ok;
    }
  });
}

function readonly(obj) {
  return new Proxy(obj, {
    get(target, key, receiver) {
      if (key === RAW_SYM) return target;
      if (key === READONLY_SYM) return true;
      return Reflect.get(target, key, receiver);
    },
    set() { return true; } // silently ignore write like Vue readonly
  });
}

function ref(initial) {
  const wrapper = {
    __v_isRef: true,
    _value: initial,
    get value() { track(wrapper, 'value'); return wrapper._value; },
    set value(v) {
      if (v !== wrapper._value) {
        wrapper._value = v;
        trigger(wrapper, 'value');
      }
    }
  };
  return wrapper;
}

function isRef(v) { return Boolean(v && v.__v_isRef); }
function unref(v) { return isRef(v) ? v.value : v; }
function toValue(v) { return typeof v === 'function' ? v() : unref(v); }
function isReactive(v) { return Boolean(v && v[REACTIVE_SYM]); }
function isReadonly(v) { return Boolean(v && v[READONLY_SYM]); }
function isProxy(v) { return isReactive(v) || isReadonly(v); }
function toRaw(v) { return (v && v[RAW_SYM]) || v; }
function markRaw(v) { Object.defineProperty(v, SKIP_SYM, { value: true }); return v; }

function toRef(obj, key) {
  return {
    __v_isRef: true,
    get value() { return obj[key]; },
    set value(v) { obj[key] = v; }
  };
}
function toRefs(obj) {
  const res = {};
  for (const k of Object.keys(obj)) res[k] = toRef(obj, k);
  return res;
}

function computed(getter) {
  let dirty = true;
  let cached;
  let computeCount = 0;
  const eff = {
    deps: new Set(),
    run() {
      const prev = activeEffect;
      activeEffect = eff;
      try { cached = getter(); computeCount++; } finally { activeEffect = prev; }
      dirty = false;
      return cached;
    },
    scheduler() {
      if (!dirty) { dirty = true; trigger(cRef, 'value'); }
    }
  };
  const cRef = {
    __v_isRef: true,
    get _computeCount() { return computeCount; },
    get value() {
      track(cRef, 'value');
      if (dirty) eff.run();
      return cached;
    }
  };
  return cRef;
}

function effectScope() {
  const stops = [];
  const cleanups = [];
  const scope = {
    active: true,
    run(fn) {
      const prev = activeScope;
      activeScope = scope;
      try { return fn(); } finally { activeScope = prev; }
    },
    recordStop(fn) { stops.push(fn); },
    onDispose(fn) { cleanups.push(fn); },
    stop() {
      if (!scope.active) return;
      scope.active = false;
      stops.forEach(s => s());
      cleanups.forEach(c => c());
    }
  };
  return scope;
}
function getCurrentScope() { return activeScope; }
function onScopeDispose(fn) { if (activeScope) activeScope.onDispose(fn); }

function watchEffect(fn, options = {}) {
  const flush = options.flush || 'pre';
  let cleanup = null;
  let stopped = false;
  const onCleanup = (cb) => { cleanup = cb; };
  const eff = {
    deps: new Set(),
    run() {
      if (stopped) return;
      if (cleanup) { cleanup(); cleanup = null; }
      const prev = activeEffect;
      activeEffect = eff;
      try { fn(onCleanup); } finally { activeEffect = prev; }
    },
    scheduler() {
      if (stopped) return;
      if (flush === 'post') Promise.resolve().then(() => eff.run());
      else eff.run();
    }
  };
  if (flush === 'post') Promise.resolve().then(() => eff.run());
  else eff.run();
  const stop = () => {
    stopped = true;
    if (cleanup) { cleanup(); cleanup = null; }
    eff.deps.forEach(d => d.delete(eff));
  };
  if (activeScope) activeScope.recordStop(stop);
  return stop;
}

function watch(source, cb) {
  let oldVal = isRef(source) ? source.value : source();
  let cleanup = null;
  const registerCleanup = (fn) => { cleanup = fn; };
  const eff = {
    deps: new Set(),
    run() {
      const prev = activeEffect;
      activeEffect = eff;
      try { isRef(source) ? source.value : source(); } finally { activeEffect = prev; }
    },
    scheduler() {
      const newVal = isRef(source) ? source.value : source();
      if (cleanup) { cleanup(); cleanup = null; }
      cb(newVal, oldVal, registerCleanup);
      oldVal = newVal;
    }
  };
  eff.run();
  return () => {
    if (cleanup) { cleanup(); cleanup = null; }
    eff.deps.forEach(d => d.delete(eff));
  };
}

window.runCompositionTests = async function () {
  // Case 1: setup + ref + reactive + computed caching + readonly + utility helpers
  const count = ref(0);
  const doubled = computed(() => count.value * 2);
  const rawObj = { label: 'init', n: 1 };
  const state = reactive(rawObj);
  const ro = readonly({ locked: 10 });
  ro.locked = 99;
  const { n: nRef } = toRefs(state);
  nRef.value = 5;
  const rawTagged = markRaw({ plain: true });

  const counterText = document.getElementById('counter-text');
  const syncDom = () => { counterText.textContent = `${count.value}/${doubled.value}`; };
  document.getElementById('counter-btn').addEventListener('click', () => {
    count.value += 1;
    syncDom();
  });
  syncDom();
  const d1 = doubled.value;
  const d2 = doubled.value; // cached!
  const computeCountBeforeClick = doubled._computeCount;
  document.getElementById('counter-btn').click();
  const computeCountAfterClick = doubled._computeCount;

  // Case 2: Lifecycle hooks mapping + provide/inject + effectScope
  const lifecycle = [];
  const provided = new Map();
  const provide = (k, v) => provided.set(k, v);
  const inject = (k, def) => (provided.has(k) ? provided.get(k) : def);
  const hooks = { onBeforeMount: [], onMounted: [], onBeforeUpdate: [], onUpdated: [], onBeforeUnmount: [], onUnmounted: [] };
  // setup runs before created/mounted
  lifecycle.push('setup');
  provide('theme', 'sky-blue');
  hooks.onBeforeMount.push(() => lifecycle.push('onBeforeMount'));
  hooks.onMounted.push(() => lifecycle.push('onMounted:' + inject('theme')));
  hooks.onBeforeUpdate.push(() => lifecycle.push('onBeforeUpdate'));
  hooks.onUpdated.push(() => lifecycle.push('onUpdated'));
  hooks.onBeforeUnmount.push(() => lifecycle.push('onBeforeUnmount'));
  hooks.onUnmounted.push(() => lifecycle.push('onUnmounted'));
  ['onBeforeMount', 'onMounted', 'onBeforeUpdate', 'onUpdated', 'onBeforeUnmount', 'onUnmounted']
    .forEach(h => hooks[h].forEach(fn => fn()));

  const scopeLog = [];
  const scopeVal = ref(1);
  const scope = effectScope();
  let currentScopeMatched = false;
  scope.run(() => {
    currentScopeMatched = (getCurrentScope() === scope);
    watchEffect(() => { scopeLog.push('eff:' + scopeVal.value); });
    onScopeDispose(() => scopeLog.push('disposed'));
  });
  scopeVal.value = 2;
  scope.stop();
  scopeVal.value = 3; // stopped, should NOT push

  // Case 3: Template ref + v-for function ref with onBeforeUpdate reset
  const rootRef = ref(null);
  const beforeMountRefIsNull = (rootRef.value === null);
  rootRef.value = document.getElementById('tpl-root');
  const mountedRefTag = rootRef.value.tagName;
  const listBox = document.getElementById('list-box');
  let divs = [];
  function renderList(items) {
    divs = []; // onBeforeUpdate reset
    listBox.innerHTML = '';
    items.forEach((item, i) => {
      const d = document.createElement('div');
      d.textContent = String(item);
      listBox.appendChild(d);
      divs[i] = d;
    });
  }
  renderList([1, 2, 3]);
  const vforInitialTexts = divs.map(d => d.textContent);
  renderList([10, 20]);
  const vforUpdatedTexts = divs.map(d => d.textContent);

  // Case 4: watchEffect pre vs flush:'post' on template ref + watch cleanup
  const domRef = ref(null);
  const preObs = [];
  const postObs = [];
  watchEffect(() => { preObs.push(domRef.value ? domRef.value.id : null); });
  watchEffect(() => { postObs.push(domRef.value ? domRef.value.id : null); }, { flush: 'post' });
  // Simulate DOM mount completing synchronously before microtask flush
  domRef.value = document.getElementById('tpl-root');
  await Promise.resolve();

  const cleanupLog = [];
  const wSrc = ref('a');
  const stopWatch = watch(wSrc, (nv, ov, onCleanup) => {
    cleanupLog.push(`change:${ov}->${nv}`);
    onCleanup(() => cleanupLog.push(`cleanup:${nv}`));
  });
  wSrc.value = 'b';
  wSrc.value = 'c';
  stopWatch();

  return {
    case1: {
      dom_after_click: counterText.textContent,
      cached_compute_before: computeCountBeforeClick,
      compute_after_click: computeCountAfterClick,
      readonly_locked: ro.locked,
      toRefs_synced_n: state.n,
      flags: {
        isRef: isRef(count),
        unref: unref(count),
        toValue: toValue(() => 7),
        isProxy: isProxy(state),
        isReactive: isReactive(state),
        isReadonly: isReadonly(ro),
        toRawEq: toRaw(state) === rawObj,
        markRawSkipped: !isReactive(reactive(rawTagged))
      }
    },
    case2: {
      lifecycle,
      scope_matched: currentScopeMatched,
      scope_log: scopeLog
    },
    case3: {
      before_mount_null: beforeMountRefIsNull,
      mounted_tag: mountedRefTag,
      vfor_initial: vforInitialTexts,
      vfor_updated: vforUpdatedTexts
    },
    case4: {
      pre_first_obs: preObs[0],
      post_first_obs: postObs[0],
      cleanup_log: cleanupLog
    }
  };
};
</script>
</body>
</html>
"""


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)
        out = page.evaluate("window.runCompositionTests()")
        browser.close()

    expected = {
        "setup_ref_reactive_computed_and_readonly": {
            "dom_after_click": "1/2",
            "cached_compute_before": 1,
            "compute_after_click": 2,
            "readonly_locked": 10,
            "toRefs_synced_n": 5,
            "flags": {
                "isRef": True,
                "unref": 1,
                "toValue": 7,
                "isProxy": True,
                "isReactive": True,
                "isReadonly": True,
                "toRawEq": True,
                "markRawSkipped": True,
            },
        },
        "lifecycle_hooks_and_provide_inject": {
            "lifecycle": [
                "setup",
                "onBeforeMount",
                "onMounted:sky-blue",
                "onBeforeUpdate",
                "onUpdated",
                "onBeforeUnmount",
                "onUnmounted",
            ],
            "scope_matched": True,
            "scope_log": ["eff:1", "eff:2", "disposed"],
        },
        "template_ref_and_v_for_function_ref": {
            "before_mount_null": True,
            "mounted_tag": "DIV",
            "vfor_initial": ["1", "2", "3"],
            "vfor_updated": ["10", "20"],
        },
        "watch_watchEffect_flush_post_and_cleanup": {
            "pre_first_obs": None,
            "post_first_obs": "tpl-root",
            "cleanup_log": ["change:a->b", "cleanup:b", "change:b->c", "cleanup:c"],
        },
    }
    mapping = [
        ("setup_ref_reactive_computed_and_readonly", out["case1"]),
        ("lifecycle_hooks_and_provide_inject", out["case2"]),
        ("template_ref_and_v_for_function_ref", out["case3"]),
        ("watch_watchEffect_flush_post_and_cleanup", 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-composition-api-lab/explore-composition-api.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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