"""Offline Playwright Chromium lab for Vue 3 Ch 29: Single-File Components (SFC)."""
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 SFC Offline Lab</title>
</head>
<body>
<div id="app1"></div>
<div id="app2"></div>
<div id="app3"></div>
<script>
// Offline SFC descriptor parser & scoped CSS compiler
function parseSFC(source) {
const tplMatch = source.match(/<template>([\s\S]*?)<\/template>/);
const scriptMatch = source.match(/<script(\s+setup)?>([\s\S]*?)<\/script>/);
const styleMatch = source.match(/<style(\s+scoped)?>([\s\S]*?)<\/style>/);
return {
template: tplMatch ? tplMatch[1].trim() : '',
script: scriptMatch ? scriptMatch[2].trim() : '',
isScriptSetup: Boolean(scriptMatch && scriptMatch[1]),
style: styleMatch ? styleMatch[2].trim() : '',
isScoped: Boolean(styleMatch && styleMatch[1])
};
}
function scopeCss(css, scopeAttr) {
return css.replace(/([^{}]+)\{/g, (_, sel) => {
const rewritten = sel.split(',').map(s => `${s.trim()}[${scopeAttr}]`).join(', ');
return `${rewritten} {`;
});
}
function compileAndMountSFC(sfcSource, mountEl, { scopeId = null, components = {} } = {}) {
const desc = parseSFC(sfcSource);
let state = {};
if (desc.script) {
if (desc.isScriptSetup) {
const fn = new Function(desc.script + '\nreturn { message };');
state = fn();
} else {
const mod = {};
const code = desc.script.replace(/export\s+default/, 'mod.default =');
new Function('mod', code)(mod);
state = mod.default && mod.default.data ? mod.default.data() : {};
}
}
let html = desc.template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_, k) => state[k] ?? '');
const wrapper = document.createElement('div');
wrapper.innerHTML = html;
if (desc.isScoped && scopeId) {
wrapper.querySelectorAll('*').forEach(el => el.setAttribute(scopeId, ''));
}
// Resolve registered child custom tags
for (const [tagName, childSfc] of Object.entries(components)) {
wrapper.querySelectorAll(tagName).forEach(placeholder => {
const host = document.createElement('div');
compileAndMountSFC(childSfc.source, host, { scopeId: childSfc.scopeId });
placeholder.replaceWith(...host.childNodes);
});
}
if (desc.style) {
const styleEl = document.createElement('style');
styleEl.textContent = (desc.isScoped && scopeId) ? scopeCss(desc.style, scopeId) : desc.style;
document.head.appendChild(styleEl);
}
mountEl.innerHTML = '';
mountEl.append(...wrapper.childNodes);
return desc;
}
window.runSfcTests = function () {
// Case 1: Basic App.vue with <template>, <script>, <style>
const app1Sfc = `
<template>
<div>
<h1 id="h1-app1">{{ message }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, Vue3 SFC!'
}
}
}
<\/script>
<style scoped>
h1 {
color: blue;
}
</style>`;
const d1 = compileAndMountSFC(app1Sfc, document.getElementById('app1'), { scopeId: 'data-v-app1' });
const h1App1 = document.getElementById('h1-app1');
// Case 2: Child SFC HelloCard.vue registered via app.component('hello-card', HelloCard)
const helloCardSfc = `
<template>
<div>
<h1 id="h1-child">{{ message }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, Child SFC!'
}
}
}
<\/script>
<style scoped>
h1 {
color: red;
}
</style>`;
const parentSfc = `
<template>
<div>
<hello-card></hello-card>
</div>
</template>`;
compileAndMountSFC(parentSfc, document.getElementById('app2'), {
components: { 'hello-card': { source: helloCardSfc, scopeId: 'data-v-card' } }
});
const h1Child = document.getElementById('h1-child');
// Case 3: <script setup> + <style scoped> isolation between parent and child h1
const scopedChildSfc = `
<template>
<h1 id="h1-scoped-child">{{ message }}</h1>
</template>
<script setup>
const message = 'Scoped Child Heading';
<\/script>
<style scoped>
h1 {
color: green;
}
</style>`;
const scopedParentSfc = `
<template>
<section>
<h1 id="h1-scoped-parent">{{ message }}</h1>
<scoped-child></scoped-child>
</section>
</template>
<script setup>
const message = 'Scoped Parent Heading';
<\/script>
<style scoped>
h1 {
color: purple;
}
</style>`;
const d3 = compileAndMountSFC(scopedParentSfc, document.getElementById('app3'), {
scopeId: 'data-v-parent3',
components: { 'scoped-child': { source: scopedChildSfc, scopeId: 'data-v-child3' } }
});
const h1P3 = document.getElementById('h1-scoped-parent');
const h1C3 = document.getElementById('h1-scoped-child');
return {
case1: {
blocks_found: Boolean(d1.template && d1.script && d1.style),
text: h1App1.textContent,
color: getComputedStyle(h1App1).color,
has_scope_attr: h1App1.hasAttribute('data-v-app1')
},
case2: {
child_text: h1Child.textContent,
child_color: getComputedStyle(h1Child).color,
has_child_scope: h1Child.hasAttribute('data-v-card')
},
case3: {
script_setup: d3.isScriptSetup,
parent_text: h1P3.textContent,
parent_color: getComputedStyle(h1P3).color,
child_text: h1C3.textContent,
child_color: getComputedStyle(h1C3).color,
styles_isolated: getComputedStyle(h1P3).color !== getComputedStyle(h1C3).color
}
};
};
</script>
</body>
</html>
"""
def main():
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML)
out = page.evaluate("window.runSfcTests()")
browser.close()
expected = {
"sfc_block_parsing_and_render": {
"blocks_found": True,
"text": "Hello, Vue3 SFC!",
"color": "rgb(0, 0, 255)",
"has_scope_attr": True,
},
"child_sfc_registration_and_mount": {
"child_text": "Hello, Child SFC!",
"child_color": "rgb(255, 0, 0)",
"has_child_scope": True,
},
"script_setup_and_scoped_style_isolation": {
"script_setup": True,
"parent_text": "Scoped Parent Heading",
"parent_color": "rgb(128, 0, 128)",
"child_text": "Scoped Child Heading",
"child_color": "rgb(0, 128, 0)",
"styles_isolated": True,
},
}
mapping = [
("sfc_block_parsing_and_render", out["case1"]),
("child_sfc_registration_and_mount", out["case2"]),
("script_setup_and_scoped_style_isolation", out["case3"]),
]
cases = [
{"name": name, "expected": expected[name], "actual": actual, "passed": actual == expected[name]}
for name, actual in mapping
]
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/vue3-sfc-lab/explore-sfc.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-sfc.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a830.zip