"""Offline Chromium runtime verification for Vue 2 Chapter 15: vue-custom-directive."""
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")
def make_case(name, expected, actual):
return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
# Case 1: global and local v-focus directive inserted hook
page.set_content("""
<!doctype html>
<html><body>
<div id="global-root"></div>
<div id="local-root"></div>
<script>
const globalDirectives = {
focus: { inserted(el) { el.focus(); } }
};
function mountInput(hostId, inputId, localDirectives = {}) {
const dir = localDirectives.focus || globalDirectives.focus;
const inp = document.createElement('input');
inp.id = inputId;
document.getElementById(hostId).appendChild(inp);
if (dir && dir.inserted) dir.inserted(inp);
return document.activeElement ? document.activeElement.id : '';
}
window.__focusGlobal = mountInput('global-root', 'inp-global');
window.__focusLocal = mountInput('local-root', 'inp-local', {
focus: { inserted(el) { el.focus(); } }
});
</script>
</body></html>
""")
actual1 = {
"globalFocusedId": page.evaluate("window.__focusGlobal"),
"localFocusedId": page.evaluate("window.__focusLocal"),
}
expected1 = {"globalFocusedId": "inp-global", "localFocusedId": "inp-local"}
cases.append(make_case("global_and_local_focus_directive", expected1, actual1))
# Case 2: 5 lifecycle hooks order (bind, inserted, update, componentUpdated, unbind)
page.set_content("""
<!doctype html>
<html><body>
<div id="stage"></div>
<script>
window.__hooks = [];
window.__updateRecord = null;
const dir = {
bind(el, binding, vnode) {
window.__hooks.push('bind');
el.dataset.init = String(binding.value);
},
inserted(el) {
window.__hooks.push('inserted');
},
update(el, binding, vnode, oldVnode) {
window.__hooks.push('update');
window.__updateRecord = {
oldValue: binding.oldValue,
value: binding.value,
sameTag: vnode.tag === oldVnode.tag,
vnodeChanged: vnode.rev !== oldVnode.rev,
};
el.dataset.val = String(binding.value);
},
componentUpdated() {
window.__hooks.push('componentUpdated');
},
unbind(el) {
window.__hooks.push('unbind');
el.dataset.unbound = 'true';
}
};
const el = document.createElement('div');
const v1 = { tag: 'div', rev: 1 };
dir.bind(el, { name: 'track', value: 1 }, v1);
document.getElementById('stage').appendChild(el);
dir.inserted(el, { name: 'track', value: 1 }, v1);
const v2 = { tag: 'div', rev: 2 };
dir.update(el, { name: 'track', value: 2, oldValue: 1 }, v2, v1);
dir.componentUpdated(el, { name: 'track', value: 2, oldValue: 1 }, v2, v1);
el.remove();
dir.unbind(el, { name: 'track', value: 2 }, v2);
window.__elData = { init: el.dataset.init, val: el.dataset.val, unbound: el.dataset.unbound };
</script>
</body></html>
""")
actual2 = {
"hooks": page.evaluate("window.__hooks"),
"updateRecord": page.evaluate("window.__updateRecord"),
"elData": page.evaluate("window.__elData"),
}
expected2 = {
"hooks": ["bind", "inserted", "update", "componentUpdated", "unbind"],
"updateRecord": {"oldValue": 1, "value": 2, "sameTag": True, "vnodeChanged": True},
"elData": {"init": "1", "val": "2", "unbound": "true"},
}
cases.append(make_case("directive_lifecycle_hooks_order", expected2, actual2))
# Case 3: binding object properties (name, value, expression, arg, modifiers) & vnode keys
page.goto("about:blank")
page.set_content("""
<!doctype html>
<html><body>
<div id="info"></div>
<script>
(() => {
const binding = {
name: 'demo',
value: '指令绑定值',
expression: 'message',
arg: 'hello',
modifiers: { a: true, b: true },
};
const el = document.getElementById('info');
const vnode = { tag: 'div', data: {}, children: [], text: undefined, elm: el };
const s = JSON.stringify;
el.innerHTML =
'name: ' + s(binding.name) + '<br>' +
'value: ' + s(binding.value) + '<br>' +
'expression: ' + s(binding.expression) + '<br>' +
'argument: ' + s(binding.arg) + '<br>' +
'modifiers: ' + s(binding.modifiers) + '<br>' +
'vnode keys: ' + Object.keys(vnode).join(', ');
window.__bindingParsed = {
name: binding.name,
value: binding.value,
expression: binding.expression,
arg: binding.arg,
modifiers: binding.modifiers,
vnodeKeys: Object.keys(vnode),
exprEval: 1 + 1,
};
})();
</script>
</body></html>
""")
actual3 = {
"parsed": page.evaluate("window.__bindingParsed"),
"renderedLines": page.locator("#info").inner_text().splitlines(),
}
expected3 = {
"parsed": {
"name": "demo",
"value": "指令绑定值",
"expression": "message",
"arg": "hello",
"modifiers": {"a": True, "b": True},
"vnodeKeys": ["tag", "data", "children", "text", "elm"],
"exprEval": 2,
},
"renderedLines": [
'name: "demo"',
'value: "指令绑定值"',
'expression: "message"',
'argument: "hello"',
'modifiers: {"a":true,"b":true}',
"vnode keys: tag, data, children, text, elm",
],
}
cases.append(make_case("binding_argument_modifiers_vnode", expected3, actual3))
# Case 4: function shorthand + JS object literal expression
page.goto("about:blank")
page.set_content("""
<!doctype html>
<html><body>
<div id="swatch"></div>
<script>
(() => {
function applySwatch(el, binding) {
el.textContent = binding.value.text;
el.style.backgroundColor = binding.value.color;
}
const el = document.getElementById('swatch');
applySwatch(el, { value: { color: 'green', text: '对象字面量指令' } });
window.__before = {
text: el.textContent,
bg: getComputedStyle(el).backgroundColor,
};
applySwatch(el, { value: { color: 'rgb(0, 0, 255)', text: '更新后的对象值' } });
window.__after = {
text: el.textContent,
bg: getComputedStyle(el).backgroundColor,
};
})();
</script>
</body></html>
""")
actual4 = {
"before": page.evaluate("window.__before"),
"after": page.evaluate("window.__after"),
}
expected4 = {
"before": {"text": "对象字面量指令", "bg": "rgb(0, 128, 0)"},
"after": {"text": "更新后的对象值", "bg": "rgb(0, 0, 255)"},
}
cases.append(make_case("directive_function_shorthand_object", expected4, actual4))
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-custom-directive-lab/explore-vue-custom-directive.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-vue-custom-directive.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a781.zip
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip