"""Offline Playwright Chromium lab for Vue 3 Chapter 13 (declarative-rendering)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue3 Declarative Rendering Offline Lab</title></head>
<body>
<section id="sec-bind">
<h1 id="msg-h1"></h1>
<h2 id="msg-rev"></h2>
<a id="site-link">点我</a>
</section>
<section id="sec-cond-list">
<div id="vis-wrap"></div>
<button id="btn-toggle">切换可见性</button>
<ul id="item-list"></ul>
</section>
<section id="sec-model-event">
<input id="msg-in" placeholder="输入一些文本" />
<p id="msg-out"></p>
<button id="btn-inc">点击我</button>
<p id="cnt-out"></p>
</section>
<section id="sec-computed">
<p id="raw-amount"></p>
<p id="tax-amount"></p>
</section>
<script>
function reactive(obj, notify) {
return new Proxy(obj, {
set(target, prop, value) {
target[prop] = value;
notify();
return true;
}
});
}
// 1. Interpolation & v-bind
const bindState = reactive({
message: 'Hello, Vue 3!',
url: 'https://example.org/vue3'
}, renderBind);
function renderBind() {
document.getElementById('msg-h1').textContent = bindState.message;
document.getElementById('msg-rev').textContent = bindState.message.split('').reverse().join('');
document.getElementById('site-link').setAttribute('href', bindState.url);
}
renderBind();
window.__bindState = bindState;
// 2. Conditional rendering (v-if) & list rendering (v-for)
const itemsArr = [
{ id: 1, name: 'Vue 3' },
{ id: 2, name: 'JavaScript' },
{ id: 3, name: 'HTML' }
];
const clState = reactive({ isVisible: true, version: 0 }, renderCondList);
function renderCondList() {
const wrap = document.getElementById('vis-wrap');
wrap.innerHTML = clState.isVisible ? '<p id="vis-msg">这段文本是可见的</p>' : '';
const ul = document.getElementById('item-list');
ul.innerHTML = '';
for (const item of itemsArr) {
const li = document.createElement('li');
li.dataset.key = String(item.id);
li.textContent = item.name;
ul.appendChild(li);
}
}
document.getElementById('btn-toggle').addEventListener('click', () => {
clState.isVisible = !clState.isVisible;
});
renderCondList();
window.__addItem = (item) => { itemsArr.push(item); clState.version++; };
// 3. v-model & v-on
const meState = reactive({ message: '', count: 0 }, renderModelEvent);
function renderModelEvent() {
const inp = document.getElementById('msg-in');
if (inp.value !== meState.message) inp.value = meState.message;
document.getElementById('msg-out').textContent = '你输入了:' + meState.message;
document.getElementById('cnt-out').textContent = '点击次数:' + meState.count;
}
document.getElementById('msg-in').addEventListener('input', (e) => {
meState.message = e.target.value;
});
document.getElementById('btn-inc').addEventListener('click', () => {
meState.count += 1;
});
renderModelEvent();
// 4. Computed amount with 10% tax
const compState = reactive({ amount: 100 }, renderComputed);
function computedAmount() {
return Number((compState.amount * 1.1).toFixed(2));
}
function renderComputed() {
document.getElementById('raw-amount').textContent = '原始金额:' + compState.amount;
document.getElementById('tax-amount').textContent = '税后金额:' + computedAmount();
}
renderComputed();
window.__compState = compState;
</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(viewport={"width": 900, "height": 600})
page.set_content(HTML_DOC)
# Case 1: Interpolation, JS expression & v-bind:href
c1 = page.evaluate("""() => {
const init = {
h1: document.getElementById('msg-h1').textContent,
rev: document.getElementById('msg-rev').textContent,
href: document.getElementById('site-link').getAttribute('href')
};
window.__bindState.message = 'Vue3!';
window.__bindState.url = 'https://vuejs.org/';
const updated = {
h1: document.getElementById('msg-h1').textContent,
rev: document.getElementById('msg-rev').textContent,
href: document.getElementById('site-link').getAttribute('href')
};
return { init, updated };
}""")
exp1 = {
"init": {"h1": "Hello, Vue 3!", "rev": "!3 euV ,olleH", "href": "https://example.org/vue3"},
"updated": {"h1": "Vue3!", "rev": "!3euV", "href": "https://vuejs.org/"},
}
cases.append({"name": "interpolation_and_vbind", "passed": c1 == exp1, "expected": exp1, "actual": c1})
# Case 2: v-if toggling & v-for keyed list reactivity
vis_init = page.evaluate("() => document.getElementById('vis-msg')?.textContent || null")
page.click("#btn-toggle")
vis_hidden = page.evaluate("() => document.getElementById('vis-msg')?.textContent || null")
page.click("#btn-toggle")
vis_restored = page.evaluate("() => document.getElementById('vis-msg')?.textContent || null")
list_init = page.evaluate("() => Array.from(document.querySelectorAll('#item-list li')).map(el => el.dataset.key + ':' + el.textContent)")
page.evaluate("() => window.__addItem({ id: 4, name: 'CSS' })")
list_after = page.evaluate("() => Array.from(document.querySelectorAll('#item-list li')).map(el => el.dataset.key + ':' + el.textContent)")
c2 = {
"vis_init": vis_init,
"vis_hidden": vis_hidden,
"vis_restored": vis_restored,
"list_init": list_init,
"list_after": list_after,
}
exp2 = {
"vis_init": "这段文本是可见的",
"vis_hidden": None,
"vis_restored": "这段文本是可见的",
"list_init": ["1:Vue 3", "2:JavaScript", "3:HTML"],
"list_after": ["1:Vue 3", "2:JavaScript", "3:HTML", "4:CSS"],
}
cases.append({"name": "conditional_and_list_rendering", "passed": c2 == exp2, "expected": exp2, "actual": c2})
# Case 3: v-model two-way binding & v-on:click counter
page.fill("#msg-in", "声明式渲染")
page.click("#btn-inc")
page.click("#btn-inc")
page.click("#btn-inc")
c3 = page.evaluate("""() => ({
input_val: document.getElementById('msg-in').value,
msg_out: document.getElementById('msg-out').textContent,
cnt_out: document.getElementById('cnt-out').textContent
})""")
exp3 = {
"input_val": "声明式渲染",
"msg_out": "你输入了:声明式渲染",
"cnt_out": "点击次数:3",
}
cases.append({"name": "vmodel_and_von_events", "passed": c3 == exp3, "expected": exp3, "actual": c3})
# Case 4: Computed tax calculation
c4 = page.evaluate("""() => {
const before = {
raw: document.getElementById('raw-amount').textContent,
tax: document.getElementById('tax-amount').textContent
};
window.__compState.amount = 250;
const after = {
raw: document.getElementById('raw-amount').textContent,
tax: document.getElementById('tax-amount').textContent
};
return { before, after };
}""")
exp4 = {
"before": {"raw": "原始金额:100", "tax": "税后金额:110"},
"after": {"raw": "原始金额:250", "tax": "税后金额:275"},
}
cases.append({"name": "computed_tax_amount", "passed": c4 == exp4, "expected": exp4, "actual": c4})
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-declarative-rendering-lab/explore-declarative-rendering.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-declarative-rendering.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a817.zip