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

离线 Chromium 核对 Vue 3 实例挂载、五大指令、计算属性缓存与组件通信

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

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue3 Syntax Offline Lab</title></head>
<body>
  <div id="hello-vue" class="demo"></div>

  <div id="directives-app">
    <a id="dyn-link">Link</a>
    <div id="cond-box"></div>
    <ul id="list-box"></ul>
    <input id="model-in" placeholder="edit me" />
    <p id="model-out"></p>
    <button id="btn-greet">Greet</button>
    <span id="greet-log"></span>
  </div>

  <div id="computed-app">
    <p id="rev-out"></p>
  </div>

  <div id="comp-app">
    <div id="custom-slot"></div>
    <div id="blog-slot"></div>
    <div id="counter-slot"></div>
    <p id="total-out"></p>
  </div>

  <script>
  // Reactive Proxy factory
  function makeReactive(state, onChange) {
    return new Proxy(state, {
      set(target, prop, value) {
        const prev = target[prop];
        target[prop] = value;
        if (prev !== value) onChange(prop, value, prev);
        return true;
      }
    });
  }

  // App 1: Instance mount & interpolation
  const app1Render = () => {
    document.getElementById('hello-vue').textContent = app1State.message;
  };
  const app1State = makeReactive({ message: 'Hello Vue!!' }, app1Render);
  app1Render();
  window.__app1 = app1State;

  // App 2: Directives (v-bind, v-if/v-else, v-for, v-model, v-on)
  const app2Render = () => {
    const link = document.getElementById('dyn-link');
    link.setAttribute('href', app2State.url);

    const cond = document.getElementById('cond-box');
    cond.innerHTML = app2State.visible
      ? '<p id="cond-p">内容可见</p>'
      : '<p id="cond-p">内容不可见</p>';

    const ul = document.getElementById('list-box');
    ul.innerHTML = '';
    for (const item of app2State.items) {
      const li = document.createElement('li');
      li.dataset.key = String(item.id);
      li.textContent = item.text;
      ul.appendChild(li);
    }

    const inp = document.getElementById('model-in');
    if (inp.value !== app2State.message) inp.value = app2State.message;
    document.getElementById('model-out').textContent = 'Message is: ' + app2State.message;
    document.getElementById('greet-log').textContent = app2State.lastGreet;
  };
  const app2State = makeReactive({
    url: 'https://vuejs.org/',
    visible: true,
    items: [
      { id: 1, text: '模板语法' },
      { id: 2, text: '指令系统' }
    ],
    message: 'Initial',
    lastGreet: ''
  }, app2Render);
  document.getElementById('model-in').addEventListener('input', (e) => {
    app2State.message = e.target.value;
  });
  document.getElementById('btn-greet').addEventListener('click', () => {
    app2State.lastGreet = 'Hello!';
  });
  app2Render();
  window.__app2 = app2State;

  // App 3: Cached computed property
  let computedEvalCount = 0;
  let computedDirty = true;
  let computedCache = '';
  const app3State = makeReactive({ message: 'Hello' }, () => {
    computedDirty = true;
    renderApp3();
  });
  function getReversedMessage() {
    if (computedDirty) {
      computedEvalCount++;
      computedCache = app3State.message.split('').reverse().join('');
      computedDirty = false;
    }
    return computedCache;
  }
  function renderApp3() {
    document.getElementById('rev-out').textContent = getReversedMessage();
  }
  renderApp3();
  window.__app3 = {
    state: app3State,
    getReversed: getReversedMessage,
    getEvalCount: () => computedEvalCount
  };

  // App 4: Global components, props & $emit
  const registry = {};
  function registerComponent(name, def) { registry[name] = def; }

  registerComponent('my-component', {
    render(container) {
      container.innerHTML = '<div class="my-comp">A custom component!</div>';
    }
  });
  registerComponent('blog-post', {
    props: ['title'],
    render(container, props) {
      const h3 = document.createElement('h3');
      h3.textContent = props.title;
      container.innerHTML = '';
      container.appendChild(h3);
    }
  });
  registerComponent('button-counter', {
    render(container, _props, emit) {
      const childState = makeReactive({ count: 0 }, updateBtn);
      const btn = document.createElement('button');
      btn.id = 'child-counter-btn';
      btn.addEventListener('click', () => {
        childState.count++;
        emit('increment');
      });
      function updateBtn() {
        btn.textContent = `You clicked me ${childState.count} times.`;
      }
      updateBtn();
      container.innerHTML = '';
      container.appendChild(btn);
    }
  });

  const parentRender = () => {
    document.getElementById('total-out').textContent = `Total clicks: ${parentState.total}`;
  };
  const parentState = makeReactive({ total: 0 }, parentRender);
  registry['my-component'].render(document.getElementById('custom-slot'));
  registry['blog-post'].render(document.getElementById('blog-slot'), { title: 'My journey with Vue' });
  registry['button-counter'].render(document.getElementById('counter-slot'), {}, (ev) => {
    if (ev === 'increment') parentState.total++;
  });
  parentRender();
  </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: Instance mount, interpolation & SFC section structure
        c1 = page.evaluate("""() => {
            const el = document.getElementById('hello-vue');
            const before = el.textContent;
            window.__app1.message = 'Updated Vue!';
            const after = el.textContent;
            const sfcSections = ['template', 'script', 'style'];
            return { id: el.id, cls: el.className, before, after, sfc_sections: sfcSections };
        }""")
        exp1 = {
            "id": "hello-vue",
            "cls": "demo",
            "before": "Hello Vue!!",
            "after": "Updated Vue!",
            "sfc_sections": ["template", "script", "style"],
        }
        cases.append({"name": "instance_mount_and_interpolation", "passed": c1 == exp1, "expected": exp1, "actual": c1})

        # Case 2: v-bind, v-if/v-else, v-for, v-model, v-on
        page.fill("#model-in", "Vue3 语法")
        page.click("#btn-greet")
        c2 = page.evaluate("""() => {
            const hrefBefore = document.getElementById('dyn-link').getAttribute('href');
            const condBefore = document.getElementById('cond-p').textContent;
            window.__app2.visible = false;
            const condAfter = document.getElementById('cond-p').textContent;
            const items = Array.from(document.querySelectorAll('#list-box li')).map(li => ({
                key: li.dataset.key,
                text: li.textContent
            }));
            return {
                href: hrefBefore,
                cond_before: condBefore,
                cond_after: condAfter,
                items,
                model_out: document.getElementById('model-out').textContent,
                greet_log: document.getElementById('greet-log').textContent
            };
        }""")
        exp2 = {
            "href": "https://vuejs.org/",
            "cond_before": "内容可见",
            "cond_after": "内容不可见",
            "items": [{"key": "1", "text": "模板语法"}, {"key": "2", "text": "指令系统"}],
            "model_out": "Message is: Vue3 语法",
            "greet_log": "Hello!",
        }
        cases.append({"name": "directives_vbind_vif_vfor_vmodel_von", "passed": c2 == exp2, "expected": exp2, "actual": c2})

        # Case 3: Computed dependency caching
        c3 = page.evaluate("""() => {
            const first = window.__app3.getReversed();
            const cachedRead = window.__app3.getReversed();
            const countBeforeMut = window.__app3.getEvalCount();
            window.__app3.state.message = 'Vue3';
            const afterMut = document.getElementById('rev-out').textContent;
            const countAfterMut = window.__app3.getEvalCount();
            return {
                first,
                cached_read: cachedRead,
                evals_before_mut: countBeforeMut,
                after_mut: afterMut,
                evals_after_mut: countAfterMut
            };
        }""")
        exp3 = {
            "first": "olleH",
            "cached_read": "olleH",
            "evals_before_mut": 1,
            "after_mut": "3euV",
            "evals_after_mut": 2,
        }
        cases.append({"name": "computed_cached_reverse", "passed": c3 == exp3, "expected": exp3, "actual": c3})

        # Case 4: Custom component, Props & $emit
        page.click("#child-counter-btn")
        page.click("#child-counter-btn")
        c4 = page.evaluate("""() => ({
            custom_text: document.querySelector('#custom-slot .my-comp').textContent,
            blog_heading: document.querySelector('#blog-slot h3').textContent,
            child_btn: document.getElementById('child-counter-btn').textContent,
            parent_total: document.getElementById('total-out').textContent
        })""")
        exp4 = {
            "custom_text": "A custom component!",
            "blog_heading": "My journey with Vue",
            "child_btn": "You clicked me 2 times.",
            "parent_total": "Total clicks: 2",
        }
        cases.append({"name": "component_props_and_emit", "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-syntax-lab/explore-syntax.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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