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

离线 Chromium 核对 createApp 挂载、setup/ref、data 代理与 methods

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-intro.py
explore-intro.py258 行
"""Offline Playwright Chromium lab for Vue 3 Chapter 11 (intro)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue3 Intro Offline Lab</title></head>
<body>
  <div id="hello-vue" class="demo">{{ message }}</div>
  <div id="setup-app">
    <button id="btn-inc" @click="increment">{{ count }}</button>
  </div>
  <div id="data-app">
    <span id="data-val">{{ count }}</span>
  </div>
  <div id="methods-app">
    <span id="method-val">{{ count }}</span>
    <button id="btn-method" @click="increment">+1</button>
  </div>

  <script>
  const MiniVue = (() => {
    function ref(initial) {
      let _val = initial;
      const subs = new Set();
      return {
        __isRef: true,
        get value() { return _val; },
        set value(v) {
          if (v !== _val) {
            _val = v;
            subs.forEach(fn => fn());
          }
        },
        _sub(fn) { subs.add(fn); }
      };
    }

    function reactive(obj, onUpdate) {
      return new Proxy(obj, {
        get(target, key, receiver) {
          return Reflect.get(target, key, receiver);
        },
        set(target, key, val, receiver) {
          const ok = Reflect.set(target, key, val, receiver);
          onUpdate();
          return ok;
        }
      });
    }

    function createApp(options) {
      return {
        mount(selector) {
          const el = typeof selector === 'string' ? document.querySelector(selector) : selector;
          const template = options.template || el.innerHTML;
          const rawData = typeof options.data === 'function' ? options.data() : {};
          const listeners = [];
          const render = () => {
            // Evaluate mustache expressions in text nodes cleanly
            el.innerHTML = template.replace(/\{\{\s*([^}]+)\s*\}\}/g, (_, expr) => {
              const key = expr.trim();
              if (setupResult && key in setupResult) {
                const v = setupResult[key];
                return v && v.__isRef ? String(v.value) : String(v);
              }
              return String(vm[key]);
            });
            // Bind @click handlers
            el.querySelectorAll('*').forEach(node => {
              if (!node.hasAttribute('@click')) return;
              const handlerName = node.getAttribute('@click').trim();
              node.removeAttribute('@click');
              node.addEventListener('click', () => {
                if (setupResult && typeof setupResult[handlerName] === 'function') {
                  setupResult[handlerName]();
                } else if (typeof vm[handlerName] === 'function') {
                  vm[handlerName]();
                }
              });
            });
          };

          const $data = reactive(rawData, render);
          const methods = options.methods || {};
          let setupResult = null;

          const vmTarget = { $data };
          const vm = new Proxy(vmTarget, {
            get(target, key) {
              if (key === '$data') return $data;
              if (key in $data) return $data[key];
              if (key in methods) return methods[key].bind(vm);
              if (setupResult && key in setupResult) {
                const v = setupResult[key];
                return v && v.__isRef ? v.value : v;
              }
              return target[key];
            },
            set(target, key, val) {
              if (key in $data) {
                $data[key] = val;
                return true;
              }
              if (setupResult && key in setupResult && setupResult[key] && setupResult[key].__isRef) {
                setupResult[key].value = val;
                return true;
              }
              target[key] = val;
              return true;
            }
          });

          if (typeof options.setup === 'function') {
            setupResult = options.setup();
            Object.values(setupResult).forEach(v => {
              if (v && v.__isRef) v._sub(render);
            });
          }

          render();
          return vm;
        }
      };
    }

    return { createApp, ref };
  })();

  window.__vms = {};

  // App 1: HelloVueApp
  const HelloVueApp = {
    data() {
      return { message: 'Hello Vue!!' };
    }
  };
  window.__vms.hello = MiniVue.createApp(HelloVueApp).mount('#hello-vue');

  // App 2: setup + ref + root container template
  const { createApp, ref } = MiniVue;
  window.__vms.setup = createApp({
    setup() {
      const count = ref(0);
      function increment() {
        count.value++;
      }
      return { count, increment };
    }
  }).mount('#setup-app');

  // App 3: data() & $data bidirectional proxy
  window.__vms.dataVm = MiniVue.createApp({
    data() {
      return { count: 4 };
    }
  }).mount('#data-app');

  // App 4: methods option with `this`
  window.__vms.methodsVm = MiniVue.createApp({
    data() {
      return { count: 4 };
    },
    methods: {
      increment() {
        this.count++;
      }
    }
  }).mount('#methods-app');
  </script>
</body>
</html>
"""


def launch_browser(pw):
    try:
        return pw.chromium.launch(headless=True)
    except Exception:
        return pw.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 900, "height": 600})
        page.set_content(HTML_DOC)

        # Case 1: createApp + mount('#hello-vue') + mustache interpolation
        c1 = page.evaluate("""() => {
            const el = document.getElementById('hello-vue');
            const initial = el.textContent.trim();
            window.__vms.hello.message = 'Vue 3 Ready';
            const updated = el.textContent.trim();
            return { id: el.id, className: el.className, initial, updated };
        }""")
        exp1 = {"id": "hello-vue", "className": "demo", "initial": "Hello Vue!!", "updated": "Vue 3 Ready"}
        cases.append({"name": "create_app_mount_mustache", "passed": c1 == exp1, "expected": exp1, "actual": c1})

        # Case 2: setup() + ref() + container innerHTML root template
        initial_btn = page.locator("#btn-inc").inner_text().strip()
        page.click("#btn-inc")
        after_1 = page.locator("#btn-inc").inner_text().strip()
        page.click("#btn-inc")
        after_2 = page.locator("#btn-inc").inner_text().strip()
        vm_count = page.evaluate("() => window.__vms.setup.count")
        c2 = {"initial": initial_btn, "after_click_1": after_1, "after_click_2": after_2, "vm_count": vm_count}
        exp2 = {"initial": "0", "after_click_1": "1", "after_click_2": "2", "vm_count": 2}
        cases.append({"name": "setup_ref_root_template", "passed": c2 == exp2, "expected": exp2, "actual": c2})

        # Case 3: data() proxy synchronization between vm.count and vm.$data.count
        c3 = page.evaluate("""() => {
            const vm = window.__vms.dataVm;
            const out = {
                init_data: vm.$data.count,
                init_vm: vm.count,
                init_dom: document.getElementById('data-val').textContent.trim()
            };
            vm.count = 5;
            out.after_vm_set_data = vm.$data.count;
            out.after_vm_set_dom = document.getElementById('data-val').textContent.trim();
            vm.$data.count = 6;
            out.after_data_set_vm = vm.count;
            out.after_data_set_dom = document.getElementById('data-val').textContent.trim();
            return out;
        }""")
        exp3 = {
            "init_data": 4,
            "init_vm": 4,
            "init_dom": "4",
            "after_vm_set_data": 5,
            "after_vm_set_dom": "5",
            "after_data_set_vm": 6,
            "after_data_set_dom": "6",
        }
        cases.append({"name": "data_proxy_sync", "passed": c3 == exp3, "expected": exp3, "actual": c3})

        # Case 4: methods option binding `this` to component instance
        init_m = page.evaluate("() => ({ count: window.__vms.methodsVm.count, dom: document.getElementById('method-val').textContent.trim() })")
        after_call = page.evaluate("() => { window.__vms.methodsVm.increment(); return { count: window.__vms.methodsVm.count, dom: document.getElementById('method-val').textContent.trim() }; }")
        page.click("#btn-method")
        after_click = page.evaluate("() => ({ count: window.__vms.methodsVm.count, dom: document.getElementById('method-val').textContent.trim() })")
        c4 = {"init": init_m, "after_vm_increment": after_call, "after_btn_click": after_click}
        exp4 = {
            "init": {"count": 4, "dom": "4"},
            "after_vm_increment": {"count": 5, "dom": "5"},
            "after_btn_click": {"count": 6, "dom": "6"},
        }
        cases.append({"name": "methods_this_increment", "passed": c4 == exp4, "expected": exp4, "actual": c4})

        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-intro-lab/explore-intro.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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