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

离线 Chromium 核对全局/局部组件隔离、scoped 样式、动态 Prop 与全量 Prop 校验

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

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>Vue3 Components Offline Lab</title>
  <style>
    [data-v-sfc1] p { color: rgb(0, 0, 255); }
  </style>
</head>
<body>
  <div id="global-app">
    <div id="greet-host"></div>
    <div id="counters-host"></div>
  </div>

  <div id="local-app-a"></div>
  <div id="local-app-b"></div>
  <div id="sfc-demo" data-v-sfc1>
    <p id="sfc-p">Hello from MyComponent</p>
  </div>
  <p id="outside-p">Outside paragraph</p>

  <div id="props-static"></div>
  <div id="props-dynamic"></div>

  <script>
  function reactive(obj, onChange) {
    return new Proxy(obj, {
      set(t, k, v) { t[k] = v; onChange(); return true; }
    });
  }

  // 1. Global component & isolated reuse instances
  const globalComponents = {};
  function registerGlobal(name, def) { globalComponents[name] = def; }

  registerGlobal('greeting-box', {
    mount(el) { el.innerHTML = '<h1>自定义组件!</h1>'; }
  });
  registerGlobal('button-counter', {
    mount(el, idx) {
      // Fresh data() object per component instance
      const state = reactive({ count: 0 }, render);
      const btn = document.createElement('button');
      btn.id = 'counter-' + idx;
      btn.addEventListener('click', () => { state.count++; });
      function render() { btn.textContent = `点了 ${state.count} 次!`; }
      render();
      el.appendChild(btn);
    }
  });

  globalComponents['greeting-box'].mount(document.getElementById('greet-host'));
  const countersHost = document.getElementById('counters-host');
  for (let i = 1; i <= 3; i++) {
    globalComponents['button-counter'].mount(countersHost, i);
  }

  // 2. Local component scope isolation
  const LocalCard = { template: '<h1>局部组件!</h1>' };
  function mountWithLocal(selector, localMap) {
    const host = document.querySelector(selector);
    if (localMap && localMap['local-card']) {
      host.innerHTML = localMap['local-card'].template;
    } else {
      host.innerHTML = '<local-card data-unresolved="true"></local-card>';
    }
  }
  mountWithLocal('#local-app-a', { 'local-card': LocalCard });
  mountWithLocal('#local-app-b', {});

  // 3. Static & Dynamic Props
  const staticTitles = ['Alpha', 'Beta', 'Gamma'];
  const staticHost = document.getElementById('props-static');
  staticTitles.forEach(t => {
    const h4 = document.createElement('h4'); h4.textContent = t; staticHost.appendChild(h4);
  });

  const dynSites = [
    { id: 1, title: 'Alpha' },
    { id: 2, title: 'Beta' },
    { id: 3, title: 'Gamma' }
  ];
  function renderDynProps() {
    const host = document.getElementById('props-dynamic');
    host.innerHTML = '';
    dynSites.forEach(site => {
      const h4 = document.createElement('h4');
      h4.textContent = `${site.id} - ${site.title}`;
      host.appendChild(h4);
    });
  }
  renderDynProps();
  window.__updateSiteTitle = (idx, title) => { dynSites[idx].title = title; renderDynProps(); };

  // 4. Prop validation engine covering all 8 native constructors + custom class + required + default + validator
  class Person { constructor(name) { this.name = name; } }
  function checkType(val, typeCtor) {
    if (typeCtor === String) return typeof val === 'string';
    if (typeCtor === Number) return typeof val === 'number';
    if (typeCtor === Boolean) return typeof val === 'boolean';
    if (typeCtor === Array) return Array.isArray(val);
    if (typeCtor === Object) return val !== null && typeof val === 'object' && !Array.isArray(val);
    if (typeCtor === Date) return val instanceof Date;
    if (typeCtor === Function) return typeof val === 'function';
    if (typeCtor === Symbol) return typeof val === 'symbol';
    return val instanceof typeCtor;
  }

  function validateProps(schema, rawProps) {
    const warnings = [];
    const resolved = {};
    for (const [key, rule] of Object.entries(schema)) {
      const def = typeof rule === 'function' || Array.isArray(rule) ? { type: rule } : rule;
      let val = rawProps[key];
      if (val === undefined) {
        if (def.required) {
          warnings.push(`missing required prop: ${key}`);
          continue;
        }
        if ('default' in def) {
          val = typeof def.default === 'function' && def.type !== Function ? def.default() : def.default;
        }
      }
      resolved[key] = val;
      if (val === null || val === undefined) continue;
      if (def.type) {
        const types = Array.isArray(def.type) ? def.type : [def.type];
        if (!types.some(t => checkType(val, t))) {
          warnings.push(`type mismatch on ${key}`);
        }
      }
      if (typeof def.validator === 'function' && !def.validator(val)) {
        warnings.push(`validator failed on ${key}`);
      }
    }
    return { resolved, warnings };
  }

  window.__runPropValidation = () => {
    const schema = {
      propA: Number,
      propB: [String, Number],
      propC: { type: String, required: true },
      propD: { type: Number, default: 100 },
      propE: { type: Object, default() { return { message: 'hello' }; } },
      propF: { validator: (v) => ['success', 'warning', 'danger'].includes(v) },
      propBool: Boolean,
      propArr: Array,
      propDate: Date,
      propFn: Function,
      propSym: Symbol,
      propPerson: Person
    };

    const valid1 = validateProps(schema, {
      propA: null,
      propB: 'ok',
      propC: 'required-text',
      propF: 'warning',
      propBool: true,
      propArr: [1, 2],
      propDate: new Date(2026, 0, 1),
      propFn: () => 1,
      propSym: Symbol('id'),
      propPerson: new Person('Ada')
    });
    const valid2 = validateProps(schema, { propC: 'second' });
    const invalid = validateProps(schema, { propA: 'not-a-num', propF: 'invalid-status' });

    return {
      valid_warnings: valid1.warnings,
      default_num: valid1.resolved.propD,
      default_obj_msg: valid1.resolved.propE.message,
      factory_distinct_refs: valid1.resolved.propE !== valid2.resolved.propE,
      invalid_warnings: invalid.warnings
    };
  };
  </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: Global component & 3 reused instances with isolated data() state
        page.click("#counter-1")
        page.click("#counter-1")
        page.click("#counter-2")
        c1 = page.evaluate("""() => ({
            greeting: document.querySelector('#greet-host h1').textContent,
            counters: [
                document.getElementById('counter-1').textContent,
                document.getElementById('counter-2').textContent,
                document.getElementById('counter-3').textContent
            ]
        })""")
        exp1 = {
            "greeting": "自定义组件!",
            "counters": ["点了 2 次!", "点了 1 次!", "点了 0 次!"],
        }
        cases.append({"name": "global_component_and_reuse_isolation", "passed": c1 == exp1, "expected": exp1, "actual": c1})

        # Case 2: Local component scope & SFC scoped style isolation
        c2 = page.evaluate("""() => ({
            app_a_h1: document.querySelector('#local-app-a h1')?.textContent || null,
            app_b_has_h1: document.querySelector('#local-app-b h1') !== null,
            app_b_unresolved: document.querySelector('#local-app-b local-card')?.dataset.unresolved === 'true',
            sfc_p_color: getComputedStyle(document.getElementById('sfc-p')).color,
            outside_p_color: getComputedStyle(document.getElementById('outside-p')).color
        })""")
        exp2 = {
            "app_a_h1": "局部组件!",
            "app_b_has_h1": False,
            "app_b_unresolved": True,
            "sfc_p_color": "rgb(0, 0, 255)",
            "outside_p_color": "rgb(0, 0, 0)",
        }
        cases.append({"name": "local_component_scope", "passed": c2 == exp2, "expected": exp2, "actual": c2})

        # Case 3: Static & dynamic props propagation
        c3 = page.evaluate("""() => {
            const statics = Array.from(document.querySelectorAll('#props-static h4')).map(el => el.textContent);
            const dynBefore = Array.from(document.querySelectorAll('#props-dynamic h4')).map(el => el.textContent);
            window.__updateSiteTitle(1, 'Beta-V2');
            const dynAfter = Array.from(document.querySelectorAll('#props-dynamic h4')).map(el => el.textContent);
            return { statics, dyn_before: dynBefore, dyn_after: dynAfter };
        }""")
        exp3 = {
            "statics": ["Alpha", "Beta", "Gamma"],
            "dyn_before": ["1 - Alpha", "2 - Beta", "3 - Gamma"],
            "dyn_after": ["1 - Alpha", "2 - Beta-V2", "3 - Gamma"],
        }
        cases.append({"name": "static_and_dynamic_props", "passed": c3 == exp3, "expected": exp3, "actual": c3})

        # Case 4: Prop validation rules (8 native ctors, custom class, defaults, validator)
        c4 = page.evaluate("() => window.__runPropValidation()")
        exp4 = {
            "valid_warnings": [],
            "default_num": 100,
            "default_obj_msg": "hello",
            "factory_distinct_refs": True,
            "invalid_warnings": [
                "type mismatch on propA",
                "missing required prop: propC",
                "validator failed on propF",
            ],
        }
        cases.append({"name": "prop_validation_rules", "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-components-lab/explore-components.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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