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

离线 Chromium 核验 Vue 2 Hello World 声明式更新、局部组件挂载与 ES5 响应式描述符

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

MINI_VUE2_JS = r"""
(function (global) {
  class Dep {
    constructor() { this.subs = new Set(); }
    depend() { if (Dep.target) this.subs.add(Dep.target); }
    notify() { this.subs.forEach(w => w.update()); }
  }
  Dep.target = null;

  class Watcher {
    constructor(vm, getter, cb) {
      this.vm = vm;
      this.getter = getter;
      this.cb = cb;
      this.value = this.get();
    }
    get() {
      Dep.target = this;
      const val = this.getter.call(this.vm, this.vm);
      Dep.target = null;
      return val;
    }
    update() {
      const oldVal = this.value;
      const newVal = this.get();
      this.value = newVal;
      if (this.cb) this.cb.call(this.vm, newVal, oldVal);
    }
  }

  function observe(data) {
    if (!data || typeof data !== 'object') return;
    Object.keys(data).forEach(key => {
      let val = data[key];
      const dep = new Dep();
      Object.defineProperty(data, key, {
        enumerable: true,
        configurable: true,
        get() { dep.depend(); return val; },
        set(newVal) {
          if (newVal === val) return;
          val = newVal;
          dep.notify();
        }
      });
    });
  }

  function evalExpr(vm, expr) {
    return new Function('with(this){ return (' + expr + '); }').call(vm);
  }

  class Vue {
    constructor(options) {
      this.$options = options || {};
      const rawData = typeof options.data === 'function' ? options.data() : (options.data || {});
      this.$data = rawData;
      observe(rawData);
      Object.keys(rawData).forEach(key => {
        Object.defineProperty(this, key, {
          enumerable: true,
          configurable: true,
          get: () => this.$data[key],
          set: (v) => { this.$data[key] = v; }
        });
      });
      this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el;
      if (this.$el) this._compile(this.$el);
    }
    _compile(node) {
      const components = this.$options.components || {};
      Array.from(node.childNodes).forEach(child => {
        if (child.nodeType === 3 && /\{\{(.+?)\}\}/.test(child.textContent)) {
          const tpl = child.textContent;
          new Watcher(this, () => tpl.replace(/\{\{(.+?)\}\}/g, (_, exp) => evalExpr(this, exp.trim())), val => {
            child.textContent = val;
          });
          child.textContent = tpl.replace(/\{\{(.+?)\}\}/g, (_, exp) => evalExpr(this, exp.trim()));
        } else if (child.nodeType === 1) {
          const tag = child.tagName.toLowerCase();
          if (components[tag]) {
            const compDef = components[tag];
            const wrapper = document.createElement('div');
            wrapper.innerHTML = compDef.template.trim();
            const compEl = wrapper.firstElementChild;
            child.parentNode.replaceChild(compEl, child);
            new Vue({ el: compEl, data: compDef.data });
          } else {
            this._compile(child);
          }
        }
      });
    }
  }
  global.Vue = Vue;
})(window);
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue 2 教程入门实验</title></head>
<body>
  <header id="static-banner">{{{{ untouched }}}}</header>
  <div id="app">
    <p id="hello-text">{{{{ message }}}}</p>
  </div>
  <section id="progressive-widget">
    <status-badge></status-badge>
  </section>
  <script>{MINI_VUE2_JS}</script>
  <script>
    window.vmHello = new Vue({{
      el: '#app',
      data: {{ message: 'Hello Vue.js!' }}
    }});
    window.vmWidget = new Vue({{
      el: '#progressive-widget',
      components: {{
        'status-badge': {{
          data: function () {{ return {{ label: 'Vue 2.x 渐进式组件', count: 1 }}; }},
          template: '<span class="badge">{{{{ label }}}} (#{{{{ count }}}})</span>'
        }}
      }}
    }});
  </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()
        page.set_content(HTML_DOC)

        # Case 1: Hello World declarative render & reactive update
        res1 = page.evaluate("""() => {
            const initial = document.querySelector('#hello-text').textContent;
            const outside = document.querySelector('#static-banner').textContent;
            window.vmHello.message = 'Hello Vue 2.x!';
            const updated = document.querySelector('#hello-text').textContent;
            return { initial, updated, outside_untouched: outside };
        }""")
        exp1 = {
            "initial": "Hello Vue.js!",
            "updated": "Hello Vue 2.x!",
            "outside_untouched": "{{ untouched }}",
        }
        cases.append({
            "name": "hello_world_declarative_render",
            "passed": res1 == exp1,
            "expected": exp1,
            "actual": res1,
        })

        # Case 2: Progressive bottom-up component adoption inside static page
        res2 = page.evaluate("""() => {
            const badge = document.querySelector('#progressive-widget .badge');
            return {
                tag: badge ? badge.tagName : null,
                text: badge ? badge.textContent : null,
                static_header_preserved: document.querySelector('#static-banner') !== null
            };
        }""")
        exp2 = {
            "tag": "SPAN",
            "text": "Vue 2.x 渐进式组件 (#1)",
            "static_header_preserved": True,
        }
        cases.append({
            "name": "progressive_component_composition",
            "passed": res2 == exp2,
            "expected": exp2,
            "actual": res2,
        })

        # Case 3: ES5 Object.defineProperty reactivity accessor verification
        res3 = page.evaluate("""() => {
            const desc = Object.getOwnPropertyDescriptor(window.vmHello.$data, 'message');
            return {
                has_getter: typeof desc.get === 'function',
                has_setter: typeof desc.set === 'function',
                proxy_matches_data: window.vmHello.message === window.vmHello.$data.message
            };
        }""")
        exp3 = {
            "has_getter": True,
            "has_setter": True,
            "proxy_matches_data": True,
        }
        cases.append({
            "name": "object_defineproperty_reactivity_core",
            "passed": res3 == exp3,
            "expected": exp3,
            "actual": res3,
        })

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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