"""Offline Playwright Chromium lab for Vue 3 Ch 23: v-model form bindings & modifiers."""
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 Forms v-model Lab</title>
</head>
<body>
<input id="text-in" value="ignored-initial-attr">
<span id="text-out"></span>
<textarea id="area-in">ignored-textarea</textarea>
<pre id="area-out"></pre>
<input type="checkbox" id="cb-single">
<input type="checkbox" class="cb-multi" id="cb-a" value="Alpha">
<input type="checkbox" class="cb-multi" id="cb-b" value="Beta">
<input type="checkbox" class="cb-multi" id="cb-c" value="Gamma">
<input type="radio" name="grp" id="rad-1" value="Vue3">
<input type="radio" name="grp" id="rad-2" value="Vite">
<select id="sel-single">
<option value="">请选择</option>
<option value="alpha.dev">Alpha</option>
<option value="beta.dev">Beta</option>
</select>
<select id="sel-multi" multiple>
<option value="alpha.dev">Alpha</option>
<option value="beta.dev">Beta</option>
<option value="gamma.dev">Gamma</option>
</select>
<select id="sel-vfor"></select>
<input type="checkbox" id="cb-custom" data-true="yes" data-false="no">
<select id="sel-obj"></select>
<input id="mod-lazy" type="text">
<input id="mod-number" type="text">
<input id="mod-trim" type="text">
<script>
const state = {
message: 'init-from-data',
message2: 'Line1\nLine2',
checked: false,
checkedNames: [],
picked: 'Vue3',
selected: '',
selectedMulti: [],
selectedVfor: 'beta.dev',
vforOptions: [
{ text: 'Alpha', value: 'alpha.dev' },
{ text: 'Beta', value: 'beta.dev' },
{ text: 'Gamma', value: 'gamma.dev' }
],
toggleCustom: 'no',
objSelected: null,
lazyMsg: 'before',
age: 0,
trimmed: ''
};
// 1. Text & textarea v-model (ignores HTML initial attributes)
const textIn = document.getElementById('text-in');
const textOut = document.getElementById('text-out');
textIn.value = state.message;
textOut.textContent = state.message;
textIn.addEventListener('input', (e) => {
state.message = e.target.value;
textOut.textContent = state.message;
});
const areaIn = document.getElementById('area-in');
const areaOut = document.getElementById('area-out');
areaIn.value = state.message2;
areaOut.textContent = state.message2;
areaIn.addEventListener('input', (e) => {
state.message2 = e.target.value;
areaOut.textContent = state.message2;
});
// 2. Checkbox (single boolean + multi array) & radio
const cbSingle = document.getElementById('cb-single');
cbSingle.checked = state.checked;
cbSingle.addEventListener('change', (e) => { state.checked = e.target.checked; });
document.querySelectorAll('.cb-multi').forEach(el => {
el.addEventListener('change', () => {
state.checkedNames = Array.from(document.querySelectorAll('.cb-multi'))
.filter(c => c.checked).map(c => c.value);
});
});
document.querySelectorAll('input[name="grp"]').forEach(el => {
el.checked = (el.value === state.picked);
el.addEventListener('change', (e) => { if (e.target.checked) state.picked = e.target.value; });
});
// 3. Select single, multiple, v-for
const selSingle = document.getElementById('sel-single');
selSingle.value = state.selected;
selSingle.addEventListener('change', (e) => { state.selected = e.target.value; });
const selMulti = document.getElementById('sel-multi');
selMulti.addEventListener('change', () => {
state.selectedMulti = Array.from(selMulti.selectedOptions).map(o => o.value);
});
const selVfor = document.getElementById('sel-vfor');
for (const opt of state.vforOptions) {
const o = document.createElement('option');
o.value = opt.value;
o.textContent = opt.text;
selVfor.appendChild(o);
}
selVfor.value = state.selectedVfor;
selVfor.addEventListener('change', (e) => { state.selectedVfor = e.target.value; });
// 4. Value binding (true-value/false-value, object option) & modifiers (.lazy, .number, .trim)
const cbCustom = document.getElementById('cb-custom');
cbCustom.checked = (state.toggleCustom === cbCustom.dataset.true);
cbCustom.addEventListener('change', (e) => {
state.toggleCustom = e.target.checked ? cbCustom.dataset.true : cbCustom.dataset.false;
});
const selObj = document.getElementById('sel-obj');
const objMap = [{ label: '123', val: { number: 123 } }, { label: '456', val: { number: 456 } }];
objMap.forEach((item, idx) => {
const o = document.createElement('option');
o.value = String(idx);
o.textContent = item.label;
selObj.appendChild(o);
});
state.objSelected = objMap[0].val;
selObj.addEventListener('change', (e) => {
state.objSelected = objMap[Number(e.target.value)].val;
});
const modLazy = document.getElementById('mod-lazy');
modLazy.addEventListener('change', (e) => { state.lazyMsg = e.target.value; });
const modNumber = document.getElementById('mod-number');
modNumber.addEventListener('input', (e) => {
const raw = e.target.value;
const n = parseFloat(raw);
state.age = Number.isNaN(n) ? raw : n;
});
const modTrim = document.getElementById('mod-trim');
modTrim.addEventListener('input', (e) => { state.trimmed = e.target.value.trim(); });
window.__state = state;
</script>
</body>
</html>
"""
def main():
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML)
initial_text_val = page.input_value("#text-in")
page.fill("#text-in", "Vue3 表单")
page.fill("#area-in", "第一行\n第二行")
page.check("#cb-single")
page.check("#cb-a")
page.check("#cb-b")
page.check("#rad-2")
page.select_option("#sel-single", "alpha.dev")
page.select_option("#sel-multi", ["alpha.dev", "gamma.dev"])
initial_vfor = page.evaluate("window.__state.selectedVfor")
page.select_option("#sel-vfor", "gamma.dev")
page.check("#cb-custom")
page.select_option("#sel-obj", "1")
# .lazy: type without blur/change first
page.focus("#mod-lazy")
page.keyboard.type("draft")
lazy_during_input = page.evaluate("window.__state.lazyMsg")
page.eval_on_selector("#mod-lazy", "el => el.blur()")
lazy_after_change = page.evaluate("window.__state.lazyMsg")
page.fill("#mod-number", "42.5")
num_valid = page.evaluate("[typeof window.__state.age, window.__state.age]")
page.fill("#mod-number", "abc")
num_nan = page.evaluate("[typeof window.__state.age, window.__state.age]")
page.fill("#mod-trim", " vue3 trim ")
st = page.evaluate("window.__state")
text_dom = page.text_content("#text-out")
area_dom = page.text_content("#area-out")
browser.close()
actuals = {
"text_and_textarea_v_model": {
"initial_ignored_attr": initial_text_val,
"text_dom": text_dom,
"area_dom": area_dom,
},
"checkbox_and_radio_bindings": {
"single_checked": st["checked"],
"multi_checked": st["checkedNames"],
"picked_radio": st["picked"],
},
"select_single_multiple_and_v_for": {
"single": st["selected"],
"multiple": st["selectedMulti"],
"vfor_initial": initial_vfor,
"vfor_updated": st["selectedVfor"],
},
"value_binding_and_modifiers": {
"custom_checkbox": st["toggleCustom"],
"object_option": st["objSelected"],
"lazy_during_input": lazy_during_input,
"lazy_after_change": lazy_after_change,
"number_valid": num_valid,
"number_nan_fallback": num_nan,
"trimmed": st["trimmed"],
},
}
expected = {
"text_and_textarea_v_model": {
"initial_ignored_attr": "init-from-data",
"text_dom": "Vue3 表单",
"area_dom": "第一行\n第二行",
},
"checkbox_and_radio_bindings": {
"single_checked": True,
"multi_checked": ["Alpha", "Beta"],
"picked_radio": "Vite",
},
"select_single_multiple_and_v_for": {
"single": "alpha.dev",
"multiple": ["alpha.dev", "gamma.dev"],
"vfor_initial": "beta.dev",
"vfor_updated": "gamma.dev",
},
"value_binding_and_modifiers": {
"custom_checkbox": "yes",
"object_option": {"number": 456},
"lazy_during_input": "before",
"lazy_after_change": "draft",
"number_valid": ["number", 42.5],
"number_nan_fallback": ["string", "abc"],
"trimmed": "vue3 trim",
},
}
cases = [
{"name": k, "expected": expected[k], "actual": actuals[k], "passed": actuals[k] == expected[k]}
for k in expected
]
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-forms-lab/explore-forms.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-forms.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a822.zip