"""Offline Playwright Chromium lab for Vue 2 Chapter 05 (vue-template-syntax)."""
import json
from playwright.sync_api import sync_playwright
MINI_VUE2_JS = r"""
(function (global) {
class Dep {
constructor() { this.subs = new Set(); }
depend() { if (Dep.target) this.subs.add(Dep.target); }
notify() { 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(data) {
Object.keys(data).forEach(key => {
let val = data[key];
const dep = new Dep();
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get() { dep.depend(); return val; },
set(newVal) {
if (newVal === val) return;
val = newVal;
dep.notify();
}
});
});
}
function evalRaw(vm, expr) {
return new Function('with(this){ return (' + expr + '); }').call(vm);
}
function splitFilters(raw) {
const parts = [];
let cur = '';
let inQuote = null;
for (let i = 0; i < raw.length; i++) {
const ch = raw[i];
if (inQuote) {
cur += ch;
if (ch === inQuote) inQuote = null;
} else if (ch === "'" || ch === '"') {
inQuote = ch;
cur += ch;
} else if (ch === '|' && raw[i - 1] !== '|' && raw[i + 1] !== '|') {
parts.push(cur.trim());
cur = '';
} else {
cur += ch;
}
}
if (cur.trim()) parts.push(cur.trim());
return parts;
}
function evalWithFilters(vm, raw) {
const parts = splitFilters(raw);
let val = evalRaw(vm, parts[0]);
const filters = vm.$options.filters || {};
for (let i = 1; i < parts.length; i++) {
const seg = parts[i];
const m = seg.match(/^([a-zA-Z_$][\w$]*)(?:\((.*)\))?$/);
if (!m) continue;
const fn = filters[m[1]];
if (!fn) continue;
const args = m[2] ? evalRaw(vm, '[' + m[2] + ']') : [];
val = fn.apply(null, [val].concat(args));
}
return val;
}
class Vue {
constructor(options) {
this.$options = 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 methods = options.methods || {};
Object.keys(methods).forEach(m => { this[m] = methods[m].bind(this); });
this.$el = document.querySelector(options.el);
if (this.$el) this._compile(this.$el);
}
_compile(node) {
Array.from(node.childNodes).forEach(child => {
if (child.nodeType === 3 && /\{\{(.+?)\}\}/.test(child.textContent)) {
const tpl = child.textContent;
const render = () => tpl.replace(/\{\{(.+?)\}\}/g, (_, exp) => evalWithFilters(this, exp.trim()));
const w = new Watcher(this, render, v => { child.textContent = v; });
child.textContent = w.value;
} else if (child.nodeType === 1) {
this._compileElement(child);
}
});
}
_compileElement(el) {
const attrs = Array.from(el.attributes);
for (const attr of attrs) {
const name = attr.name;
const exp = attr.value.trim();
if (name === 'v-html') {
el.removeAttribute(name);
const w = new Watcher(this, () => evalRaw(this, exp), v => { el.innerHTML = v; });
el.innerHTML = w.value;
} else if (name === 'v-if') {
el.removeAttribute(name);
const anchor = document.createComment('v-if');
const parent = el.parentNode;
parent.insertBefore(anchor, el);
const apply = (cond) => {
if (cond) {
if (!el.parentNode) parent.insertBefore(el, anchor.nextSibling);
} else {
if (el.parentNode) parent.removeChild(el);
}
};
const w = new Watcher(this, () => Boolean(evalRaw(this, exp)), apply);
apply(w.value);
} else if (name === 'v-model') {
el.removeAttribute(name);
if (el.type === 'checkbox') {
const w = new Watcher(this, () => Boolean(evalRaw(this, exp)), v => { el.checked = v; });
el.checked = w.value;
el.addEventListener('change', () => { this[exp] = el.checked; });
} else {
const w = new Watcher(this, () => evalRaw(this, exp), v => { el.value = v; });
el.value = w.value;
el.addEventListener('input', () => { this[exp] = el.value; });
}
} else if (name.startsWith('v-bind:') || name.startsWith(':')) {
el.removeAttribute(name);
const arg = name.startsWith(':') ? name.slice(1) : name.slice(7);
const applyAttr = (v) => {
if (arg === 'class' && typeof v === 'object' && v !== null) {
Object.keys(v).forEach(cls => { el.classList.toggle(cls, Boolean(v[cls])); });
} else {
el.setAttribute(arg, v);
}
};
const w = new Watcher(this, () => evalWithFilters(this, exp), applyAttr);
applyAttr(w.value);
} else if (name.startsWith('v-on:') || name.startsWith('@')) {
el.removeAttribute(name);
const rawEvent = name.startsWith('@') ? name.slice(1) : name.slice(5);
const segs = rawEvent.split('.');
const evtName = segs[0];
const mods = new Set(segs.slice(1));
el.addEventListener(evtName, (e) => {
if (mods.has('prevent')) e.preventDefault();
if (mods.has('stop')) e.stopPropagation();
if (typeof this[exp] === 'function') this[exp](e);
else new Function('$event', 'with(this){ ' + exp + ' }').call(this, e);
});
}
}
this._compile(el);
}
}
global.Vue = Vue;
})(window);
"""
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue 2 模板语法实验</title>
<style>
.class1 {{ background-color: #444444; color: #eeeeee; }}
</style>
</head>
<body>
<div id="app">
<p id="txt-escape">{{{{ rawHtml }}}}</p>
<div id="html-box" v-html="rawHtml"></div>
<p id="expr-sum">{{{{ 5 + 5 }}}}</p>
<p id="expr-tern">{{{{ ok ? 'YES' : 'NO' }}}}</p>
<p id="expr-rev">{{{{ code.split('').reverse().join('') }}}}</p>
<div id="expr-id-target" v-bind:id="'list-' + id">动态ID节点</div>
<input id="chk-use" type="checkbox" v-model="use">
<div id="class-box" v-bind:class="{{ 'class1': use }}">v-bind:class 指令</div>
<p id="seen-p" v-if="seen">现在你看到我了</p>
<a id="link-full" v-bind:href="url">完整绑定</a>
<a id="link-short" :href="url">缩写绑定</a>
<button id="btn-full" type="button" v-on:click="bump">完整监听</button>
<button id="btn-short" type="button" @click="bump">缩写监听</button>
<form id="demo-form" v-on:submit.prevent="onSubmit">
<button id="btn-submit" type="submit">提交</button>
</form>
<p id="model-out">{{{{ message }}}}</p>
<input id="model-in" v-model="message">
<button id="btn-reverse" type="button" v-on:click="reverseMessage">反转字符串</button>
<p id="flt-cap">{{{{ word | capitalize }}}}</p>
<div id="flt-bind" v-bind:data-code="rawId | formatId">filter-bind</div>
<p id="flt-chain">{{{{ word | capitalize | shout }}}}</p>
<p id="flt-args">{{{{ word | wrap('arg1', arg2) }}}}</p>
</div>
<script>{MINI_VUE2_JS}</script>
<script>
window.lastSubmitPrevented = false;
window.submitCount = 0;
window.clickCount = 0;
window.vm = new Vue({{
el: '#app',
data: {{
rawHtml: '<h1>蓝色天空</h1>',
ok: true,
code: 'MBSKY',
id: 1,
use: false,
seen: true,
url: 'https://www.mbsky.com',
message: 'Mbsky!',
word: 'mbsky',
rawId: 42,
arg2: 'v2'
}},
methods: {{
bump: function () {{ window.clickCount += 1; }},
onSubmit: function (e) {{
window.lastSubmitPrevented = e.defaultPrevented;
window.submitCount += 1;
}},
reverseMessage: function () {{
this.message = this.message.split('').reverse().join('');
}}
}},
filters: {{
capitalize: function (value) {{
if (!value) return '';
value = value.toString();
return value.charAt(0).toUpperCase() + value.slice(1);
}},
formatId: function (v) {{ return 'item-' + v; }},
shout: function (v) {{ return v + '!'; }},
wrap: function (v, a1, a2) {{ return '[' + a1 + ':' + v + ':' + a2 + ']'; }}
}}
}});
</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: Text interpolation, v-html & JS expressions
res1 = page.evaluate("""() => ({
escaped_text: document.getElementById('txt-escape').textContent,
v_html_tag: document.querySelector('#html-box h1').tagName,
v_html_text: document.querySelector('#html-box h1').textContent,
expr_sum: document.getElementById('expr-sum').textContent,
expr_tern: document.getElementById('expr-tern').textContent,
expr_rev: document.getElementById('expr-rev').textContent,
dynamic_id_exists: document.getElementById('list-1') !== null
})""")
exp1 = {
"escaped_text": "<h1>蓝色天空</h1>",
"v_html_tag": "H1",
"v_html_text": "蓝色天空",
"expr_sum": "10",
"expr_tern": "YES",
"expr_rev": "YKSBM",
"dynamic_id_exists": True,
}
cases.append({
"name": "interpolation_text_html_and_expressions",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: Directives (v-bind:class, v-if, v-bind:href/:href, v-on:click/@click)
before_cls = page.eval_on_selector("#class-box", "el => el.classList.contains('class1')")
page.click("#chk-use")
after_cls = page.eval_on_selector("#class-box", "el => ({ has: el.classList.contains('class1'), bg: getComputedStyle(el).backgroundColor })")
page.click("#btn-full")
page.click("#btn-short")
res2 = page.evaluate("""() => {
const seenBefore = document.getElementById('seen-p') !== null;
window.vm.seen = false;
const seenAfter = document.getElementById('seen-p') !== null;
return {
seen_before: seenBefore,
seen_after: seenAfter,
href_full: document.getElementById('link-full').getAttribute('href'),
href_short: document.getElementById('link-short').getAttribute('href'),
click_count: window.clickCount
};
}""")
res2["class1_before"] = before_cls
res2["class1_after"] = after_cls["has"]
res2["class1_bg"] = after_cls["bg"]
exp2 = {
"seen_before": True,
"seen_after": False,
"href_full": "https://www.mbsky.com",
"href_short": "https://www.mbsky.com",
"click_count": 2,
"class1_before": False,
"class1_after": True,
"class1_bg": "rgb(68, 68, 68)",
}
cases.append({
"name": "directives_v_bind_v_if_args_and_shorthands",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: .prevent event modifier on form submit
page.click("#btn-submit")
res3 = page.evaluate("""() => ({
default_prevented: window.lastSubmitPrevented,
submit_count: window.submitCount
})""")
exp3 = {"default_prevented": True, "submit_count": 1}
cases.append({
"name": "event_modifier_prevent_default",
"passed": res3 == exp3,
"expected": exp3,
"actual": res3,
})
# Case 4: v-model two-way binding + v-on string reverse
page.fill("#model-in", "Vue2!")
after_input = page.text_content("#model-out")
page.click("#btn-reverse")
res4 = {
"after_input": after_input,
"after_reverse_text": page.text_content("#model-out"),
"after_reverse_input_val": page.input_value("#model-in"),
}
exp4 = {
"after_input": "Vue2!",
"after_reverse_text": "!2euV",
"after_reverse_input_val": "!2euV",
}
cases.append({
"name": "v_model_and_v_on_reverse_message",
"passed": res4 == exp4,
"expected": exp4,
"actual": res4,
})
# Case 5: Filters (single, v-bind, chained, parameterized)
res5 = page.evaluate("""() => ({
capitalize: document.getElementById('flt-cap').textContent,
v_bind_filter: document.getElementById('flt-bind').getAttribute('data-code'),
chained: document.getElementById('flt-chain').textContent,
with_args: document.getElementById('flt-args').textContent
})""")
exp5 = {
"capitalize": "Mbsky",
"v_bind_filter": "item-42",
"chained": "Mbsky!",
"with_args": "[arg1:mbsky:v2]",
}
cases.append({
"name": "filters_single_chain_and_args",
"passed": res5 == exp5,
"expected": exp5,
"actual": res5,
})
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-template-syntax-lab/explore-vue-template-syntax.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-vue-template-syntax.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a792.zip