"""Offline Playwright Chromium lab for Vue 3 Ch 21: class and style binding."""
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 Class & Style Binding Lab</title>
<style>
.static { padding: 4px; }
.active { background-color: rgb(0, 128, 0); }
.text-danger { background-color: rgb(255, 0, 0); color: rgb(255, 255, 255); }
.classA { border-width: 1px; }
.classB { border-style: solid; }
.classC { margin-top: 2px; }
.classD { margin-bottom: 2px; }
</style>
</head>
<body>
<div id="c1"></div>
<div id="c2"></div>
<div id="c3"></div>
<div id="c4"></div>
<div id="s1">Vue3 样式绑定</div>
<div id="s2">样式数组合并</div>
<div id="s3">多重值回退</div>
<div id="comp-single"></div>
<div id="comp-multi"></div>
<script>
// Minimal ES Proxy reactivity + Vue 3 class/style binding semantics (offline)
function normalizeClass(value) {
let res = [];
if (typeof value === 'string') {
res.push(value);
} else if (Array.isArray(value)) {
for (const item of value) {
const normalized = normalizeClass(item);
if (normalized) res.push(normalized);
}
} else if (value && typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key]) res.push(key);
}
}
return res.join(' ').trim().replace(/\s+/g, ' ');
}
function applyClass(el, staticClass, dynamicBinding) {
const parts = [];
if (staticClass) parts.push(staticClass);
const dyn = normalizeClass(dynamicBinding);
if (dyn) parts.push(dyn);
el.className = parts.join(' ').trim();
}
function applyStyle(el, styleBinding) {
el.removeAttribute('style');
const objects = Array.isArray(styleBinding) ? styleBinding : [styleBinding];
for (const obj of objects) {
if (!obj) continue;
for (const [prop, val] of Object.entries(obj)) {
const cssProp = prop.replace(/[A-Z]/g, m => '-' + m.toLowerCase());
if (Array.isArray(val)) {
for (const candidate of val) {
el.style.setProperty(cssProp, candidate);
}
} else if (val != null) {
el.style.setProperty(cssProp, String(val));
}
}
}
}
function reactive(target, onChange) {
return new Proxy(target, {
set(obj, prop, val) {
obj[prop] = val;
onChange();
return true;
}
});
}
window.runAllTests = function () {
// Case 1: Object syntax + static coexistence + computed classObject
const el1 = document.getElementById('c1');
const el2 = document.getElementById('c2');
const state1 = reactive({ isActive: false, hasError: true, error: null }, render1);
function computedClassObject() {
return {
active: state1.isActive && !state1.error,
'text-danger': !!(state1.error && state1.error.type === 'fatal')
};
}
function render1() {
applyClass(el1, 'static', { active: state1.isActive, 'text-danger': state1.hasError });
applyClass(el2, 'static', computedClassObject());
}
render1();
const initialClass = el1.className;
const initialBg = getComputedStyle(el1).backgroundColor;
state1.isActive = true;
const bothClass = el1.className;
const computedOk = el2.className;
state1.error = { type: 'fatal' };
const computedFatal = el2.className;
// Case 2: Array syntax + ternary
const el3 = document.getElementById('c3');
const el4 = document.getElementById('c4');
const arrState = reactive({ isActive: false, activeClass: 'active', errorClass: 'text-danger' }, render2);
function render2() {
applyClass(el3, 'static', [arrState.activeClass, arrState.errorClass]);
applyClass(el4, 'static', [arrState.isActive ? arrState.activeClass : '', arrState.errorClass]);
}
render2();
const arrStatic = el3.className;
const ternaryFalse = el4.className;
arrState.isActive = true;
const ternaryTrue = el4.className;
// Case 3: Inline style object, array merge, and multi-value array
const s1 = document.getElementById('s1');
const s2 = document.getElementById('s2');
const s3 = document.getElementById('s3');
applyStyle(s1, { color: 'red', fontSize: 30 + 'px' });
const baseStyles = { color: 'green', fontSize: '20px', fontWeight: 'bold' };
const overridingStyles = { color: 'blue', fontSize: '32px' };
applyStyle(s2, [baseStyles, overridingStyles]);
applyStyle(s3, { display: ['-webkit-box', '-ms-flexbox', 'flex'] });
// Case 4: Component class fallthrough (single root vs multi-root $attrs.class)
const singleHost = document.getElementById('comp-single');
const h1 = document.createElement('h1');
h1.textContent = 'Single Root';
applyClass(h1, 'classA classB', 'classC classD');
singleHost.appendChild(h1);
const multiHost = document.getElementById('comp-multi');
const attrs = { class: 'classA' };
const p = document.createElement('p');
p.textContent = 'Forwarded Root';
applyClass(p, '', attrs.class);
const span = document.createElement('span');
span.textContent = 'Sibling Root';
multiHost.append(p, span);
return {
case1: {
initial_class: initialClass,
initial_bg: initialBg,
after_active_true: bothClass,
computed_active: computedOk,
computed_fatal: computedFatal
},
case2: {
array_class: arrStatic,
ternary_false: ternaryFalse,
ternary_true: ternaryTrue
},
case3: {
inline_color: getComputedStyle(s1).color,
inline_font_size: getComputedStyle(s1).fontSize,
merged_color: getComputedStyle(s2).color,
merged_font_size: getComputedStyle(s2).fontSize,
merged_font_weight: getComputedStyle(s2).fontWeight,
multi_display: getComputedStyle(s3).display
},
case4: {
single_root_class: h1.className,
multi_root_p_class: p.className,
multi_root_span_class: span.className
}
};
};
</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.runAllTests()")
browser.close()
expected = {
"class_object_and_computed_binding": {
"initial_class": "static text-danger",
"initial_bg": "rgb(255, 0, 0)",
"after_active_true": "static active text-danger",
"computed_active": "static active",
"computed_fatal": "static text-danger",
},
"class_array_and_ternary_syntax": {
"array_class": "static active text-danger",
"ternary_false": "static text-danger",
"ternary_true": "static active text-danger",
},
"style_object_array_and_multi_value": {
"inline_color": "rgb(255, 0, 0)",
"inline_font_size": "30px",
"merged_color": "rgb(0, 0, 255)",
"merged_font_size": "32px",
"merged_font_weight": "700",
"multi_display": "flex",
},
"component_single_and_multi_root_attrs": {
"single_root_class": "classA classB classC classD",
"multi_root_p_class": "classA",
"multi_root_span_class": "",
},
}
mapping = [
("class_object_and_computed_binding", out["case1"]),
("class_array_and_ternary_syntax", out["case2"]),
("style_object_array_and_multi_value", out["case3"]),
("component_single_and_multi_root_attrs", out["case4"]),
]
cases = []
for name, actual in mapping:
exp = expected[name]
cases.append({
"name": name,
"expected": exp,
"actual": actual,
"passed": actual == exp,
})
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-class-bind-lab/explore-class-bind.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-class-bind.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a812.zip