"""Offline Playwright Chromium lab for Vue 2 Chapter 10 (vue-class-style)."""
import json
from playwright.sync_api import sync_playwright
MINI_VUE2_STYLE_JS = r"""
(function (global) {
class Dep {
constructor() { this.subs = new Set(); }
depend() { if (Dep.target) this.subs.add(Dep.target); }
notify() { Array.from(this.subs).forEach(w => w.update()); }
}
Dep.target = null;
class Watcher {
constructor(vm, getter, cb) {
this.vm = vm;
this.getter = getter;
this.cb = cb;
this.value = this.get();
}
get() {
Dep.target = this;
const v = this.getter.call(this.vm);
Dep.target = null;
return v;
}
update() {
const oldVal = this.value;
const newVal = this.get();
this.value = newVal;
if (this.cb) this.cb.call(this.vm, newVal, oldVal);
}
}
function observe(obj) {
if (!obj || typeof obj !== 'object') return;
Object.keys(obj).forEach(key => {
let val = obj[key];
if (val && typeof val === 'object') observe(val);
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() { dep.depend(); return val; },
set(newVal) {
if (newVal === val) return;
val = newVal;
if (val && typeof val === 'object') observe(val);
dep.notify();
}
});
});
}
function evalExpr(vm, expr) {
return new Function('with(this){ return (' + expr + '); }').call(vm);
}
function resolveClasses(val) {
const out = [];
if (typeof val === 'string') {
val.split(/\s+/).filter(Boolean).forEach(c => out.push(c));
} else if (Array.isArray(val)) {
val.forEach(item => resolveClasses(item).forEach(c => out.push(c)));
} else if (val && typeof val === 'object') {
Object.keys(val).forEach(k => { if (val[k]) out.push(k); });
}
return out;
}
function applyStyleBinding(el, val) {
el.removeAttribute('style');
const objs = Array.isArray(val) ? val : [val];
for (const obj of objs) {
if (!obj || typeof obj !== 'object') continue;
Object.keys(obj).forEach(prop => {
el.style[prop] = obj[prop];
});
}
}
class Vue {
constructor(options) {
this.$data = options.data || {};
observe(this.$data);
Object.keys(this.$data).forEach(k => {
Object.defineProperty(this, k, {
enumerable: true,
configurable: true,
get: () => this.$data[k],
set: (v) => { this.$data[k] = v; }
});
});
const computed = options.computed || {};
Object.keys(computed).forEach(k => {
Object.defineProperty(this, k, {
enumerable: true,
configurable: true,
get: () => computed[k].call(this)
});
});
this.$el = document.querySelector(options.el);
if (this.$el) this._compile(this.$el);
}
_compile(root) {
root.querySelectorAll('*').forEach(el => {
const staticClasses = (el.getAttribute('class') || '').split(/\s+/).filter(Boolean);
Array.from(el.attributes).forEach(attr => {
if (attr.name === 'v-bind:class' || attr.name === ':class') {
const exp = attr.value.trim();
el.removeAttribute(attr.name);
const apply = (val) => {
const dyn = resolveClasses(val);
el.className = staticClasses.concat(dyn).join(' ');
};
const w = new Watcher(this, () => evalExpr(this, exp), apply);
apply(w.value);
} else if (attr.name === 'v-bind:style' || attr.name === ':style') {
const exp = attr.value.trim();
el.removeAttribute(attr.name);
const apply = (val) => applyStyleBinding(el, val);
const w = new Watcher(this, () => evalExpr(this, exp), apply);
apply(w.value);
}
});
});
}
}
global.Vue = Vue;
})(window);
"""
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue 2 样式绑定 class 与 style 实验</title>
<style>
.static {{ width: 100px; height: 100px; }}
.active {{ width: 100px; height: 100px; background-color: green; }}
.text-danger {{ background-color: red; }}
.base {{ border: 2px solid #222; }}
</style>
</head>
<body>
<div id="app">
<div id="c1" v-bind:class="{{ 'active': isActive }}"></div>
<div id="c2" class="static" v-bind:class="{{ 'active': isActive, 'text-danger': hasError }}"></div>
<div id="c3" class="static" v-bind:class="dataClassObj"></div>
<div id="c4" v-bind:class="computedClassObj"></div>
<div id="c5" v-bind:class="[activeClass, errorClass]"></div>
<div id="c6" v-bind:class="[errorClass, isActive ? activeClass : '']"></div>
<div id="s1" v-bind:style="{{ color: activeColor, fontSize: fontSize + 'px' }}">蓝色天空</div>
<div id="s2" v-bind:style="styleObject">蓝色天空</div>
<div id="s3" v-bind:style="[baseStyles, overridingStyles]">蓝色天空</div>
</div>
<script>{MINI_VUE2_STYLE_JS}</script>
<script>
window.vm = new Vue({{
el: '#app',
data: {{
isActive: true,
hasError: true,
dataClassObj: {{ active: true, 'text-danger': true }},
error: {{ value: true, type: 'fatal' }},
activeClass: 'active',
errorClass: 'text-danger',
activeColor: 'green',
fontSize: 30,
styleObject: {{ color: 'green', fontSize: '30px' }},
baseStyles: {{ color: 'green', fontSize: '30px' }},
overridingStyles: {{ color: '#dc2626', fontSize: '28px', fontWeight: '700', transform: 'translateX(10px)' }}
}},
computed: {{
computedClassObj: function () {{
return {{
base: true,
active: this.isActive && !this.error.value,
'text-danger': this.error.value && this.error.type === 'fatal'
}};
}}
}}
}});
</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()
page.set_content(HTML_DOC)
# Case 1: Object syntax single, multi + static coexistence, data object binding
res1 = page.evaluate("""() => {
const c1 = document.getElementById('c1');
const c2 = document.getElementById('c2');
const c3 = document.getElementById('c3');
const c1True = { cls: c1.className, bg: getComputedStyle(c1).backgroundColor };
const c2Cls = c2.className;
const c2Bg = getComputedStyle(c2).backgroundColor;
const c3Cls = c3.className;
const c3Bg = getComputedStyle(c3).backgroundColor;
window.vm.isActive = false;
const c1False = c1.className;
window.vm.isActive = true;
return {
c1_true_class: c1True.cls,
c1_true_bg: c1True.bg,
c1_false_class: c1False,
c2_class: c2Cls,
c2_bg_overridden: c2Bg,
c3_matches_c2: (c3Cls === c2Cls && c3Bg === c2Bg)
};
}""")
exp1 = {
"c1_true_class": "active",
"c1_true_bg": "rgb(0, 128, 0)",
"c1_false_class": "",
"c2_class": "static active text-danger",
"c2_bg_overridden": "rgb(255, 0, 0)",
"c3_matches_c2": True,
}
cases.append({
"name": "class_object_single_multi_and_data_obj",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: Computed property returning class object
res2 = page.evaluate(r"""() => {
const c4 = document.getElementById('c4');
const fatalClasses = c4.className.split(/\s+/).filter(Boolean);
window.vm.error.value = false;
const clearedClasses = c4.className.split(/\s+/).filter(Boolean);
return { fatal_classes: fatalClasses, cleared_classes: clearedClasses };
}""")
exp2 = {
"fatal_classes": ["base", "text-danger"],
"cleared_classes": ["base", "active"],
}
cases.append({
"name": "class_computed_object_pattern",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: Array syntax and ternary expression inside class array
res3 = page.evaluate("""() => {
const c5 = document.getElementById('c5');
const c6 = document.getElementById('c6');
const c6Active = c6.className;
window.vm.isActive = false;
const c6Inactive = c6.className;
return {
c5_class: c5.className,
c6_active_class: c6Active,
c6_inactive_class: c6Inactive
};
}""")
exp3 = {
"c5_class": "active text-danger",
"c6_active_class": "text-danger active",
"c6_inactive_class": "text-danger",
}
cases.append({
"name": "class_array_and_ternary_syntax",
"passed": res3 == exp3,
"expected": exp3,
"actual": res3,
})
# Case 4: Inline style object, bound data styleObject, array override & transform
res4 = page.evaluate("""() => {
const s1 = getComputedStyle(document.getElementById('s1'));
const s2 = getComputedStyle(document.getElementById('s2'));
const s3 = getComputedStyle(document.getElementById('s3'));
return {
s1_color: s1.color,
s1_font_size: s1.fontSize,
s2_matches_s1: (s2.color === s1.color && s2.fontSize === s1.fontSize),
s3_color: s3.color,
s3_font_size: s3.fontSize,
s3_font_weight: s3.fontWeight,
s3_transform: s3.transform
};
}""")
exp4 = {
"s1_color": "rgb(0, 128, 0)",
"s1_font_size": "30px",
"s2_matches_s1": True,
"s3_color": "rgb(220, 38, 38)",
"s3_font_size": "28px",
"s3_font_weight": "700",
"s3_transform": "matrix(1, 0, 0, 1, 10, 0)",
}
cases.append({
"name": "inline_style_object_data_array_and_transform",
"passed": res4 == exp4,
"expected": exp4,
"actual": res4,
})
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/vue2-vue-class-style-lab/explore-vue-class-style.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-vue-class-style.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a777.zip