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

离线实测 App.vue 属性更新、SFC 符号静态解析与 scoped 样式隔离

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-vscode.py
explore-vscode.py166 行
"""Offline Playwright Chromium verification for Vue 3 Ch04 (vscode)."""
import json
import re
from playwright.sync_api import sync_playwright


def launch_browser(p):
    for kwargs in (
        dict(headless=True),
        dict(headless=True, channel="chrome"),
        dict(headless=True, channel="msedge"),
    ):
        try:
            return p.chromium.launch(**kwargs)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


APP_VUE_BEFORE = """<script setup>
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'
import { computed } from 'vue'
const greeting = computed(() => 'You did it!')
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="./assets/logo.svg" width="125" height="125" />
    <div class="wrapper">
      <HelloWorld msg="You did it!" v-bind:class="active" />
    </div>
  </header>
  <main>
    <TheWelcome />
  </main>
</template>

<style scoped>
.logo {
  display: block;
  margin: 0 auto 32px;
}
</style>"""


def case_sfc_template_prop_update(page):
    updated_sfc = APP_VUE_BEFORE.replace('msg="You did it!"', 'msg="Hello World!"')
    msg_before = re.search(r'<HelloWorld\s+msg="([^"]+)"', APP_VUE_BEFORE).group(1)
    msg_after = re.search(r'<HelloWorld\s+msg="([^"]+)"', updated_sfc).group(1)

    svg_data = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='125' height='125'><rect width='125' height='125' fill='%2342b883'/></svg>"
    html = f"""<!doctype html><html><head><meta charset="utf-8"></head><body>
    <header>
      <img alt="Vue logo" class="logo" src="{svg_data}" width="125" height="125" />
      <div class="wrapper"><h1 id="hw-msg">{msg_before}</h1></div>
    </header>
    <main id="welcome-slot">TheWelcome</main>
    <script>
      window.__before = document.getElementById("hw-msg").textContent;
      document.getElementById("hw-msg").textContent = {json.dumps(msg_after)};
      window.__after = document.getElementById("hw-msg").textContent;
    </script></body></html>"""
    page.set_content(html)
    actual = page.evaluate("({before: window.__before, after: window.__after, imgW: document.querySelector('.logo').width, hasMain: !!document.querySelector('main')})")
    expected = {"before": "You did it!", "after": "Hello World!", "imgW": 125, "hasMain": True}
    return dict(name="sfc_template_prop_update", expected=expected, actual=actual, passed=(actual == expected))


def case_sfc_language_service_symbols():
    imports = re.findall(r"import\s+(\{[^}]+\}|\w+)\s+from\s+'([^']+)'", APP_VUE_BEFORE)
    template = re.search(r"<template>([\s\S]*?)</template>", APP_VUE_BEFORE).group(1)
    components = re.findall(r"<([A-Z]\w+)\b", template)
    directives = re.findall(r"\b(v-[a-z-]+(?::[a-z-]+)?)", template)
    lines = APP_VUE_BEFORE.splitlines()
    hw_import_line = next(i + 1 for i, ln in enumerate(lines) if "import HelloWorld" in ln)
    actual = {
        "import_sources": [src for _, src in imports],
        "template_components": components,
        "directives": directives,
        "hello_world_def_line": hw_import_line,
    }
    expected = {
        "import_sources": ["./components/HelloWorld.vue", "./components/TheWelcome.vue", "vue"],
        "template_components": ["HelloWorld", "TheWelcome"],
        "directives": ["v-bind:class"],
        "hello_world_def_line": 2,
    }
    return dict(name="sfc_language_service_symbols", expected=expected, actual=actual, passed=(actual == expected))


def case_scaffold_commands_and_dev_port():
    commands = [
        "npm create vue@latest",
        "cd my-vue3-app",
        "npm install",
        "npm run dev",
        "code .",
    ]
    options = [
        "TypeScript", "JSX", "Vue Router", "Pinia", "Vitest", "E2E", "ESLint"
    ]
    actual = {
        "entry_cmd": commands[0],
        "open_ide_cmd": commands[-1],
        "dev_url": "http://localhost:5173",
        "option_count": len(options),
        "recommended_ext": "Vue - Official",
    }
    expected = {
        "entry_cmd": "npm create vue@latest",
        "open_ide_cmd": "code .",
        "dev_url": "http://localhost:5173",
        "option_count": 7,
        "recommended_ext": "Vue - Official",
    }
    return dict(name="scaffold_commands_and_dev_port", expected=expected, actual=actual, passed=(actual == expected))


def case_scoped_style_isolation_chromium(page):
    html = """<!doctype html><html><head><meta charset="utf-8">
    <style>
      .logo[data-v-app] { display: block; margin-bottom: 32px; }
    </style></head><body>
    <img id="scoped-logo" class="logo" data-v-app width="125" height="125" />
    <img id="outside-logo" class="logo" width="125" height="125" />
    </body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => {
        const s = getComputedStyle(document.getElementById('scoped-logo'));
        const o = getComputedStyle(document.getElementById('outside-logo'));
        return {
            scopedDisplay: s.display,
            scopedMarginBottom: s.marginBottom,
            outsideDisplay: o.display,
            outsideMarginBottom: o.marginBottom
        };
    }""")
    expected = {
        "scopedDisplay": "block",
        "scopedMarginBottom": "32px",
        "outsideDisplay": "inline",
        "outsideMarginBottom": "0px",
    }
    return dict(name="scoped_style_isolation_chromium", expected=expected, actual=actual, passed=(actual == expected))


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            cases = [
                case_sfc_template_prop_update(page),
                case_sfc_language_service_symbols(),
                case_scaffold_commands_and_dev_port(),
                case_scoped_style_isolation_chromium(page),
            ]
        finally:
            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-vscode-lab/explore-vscode.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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