Vue.js 自定义指令
核对全局与局部自定义指令注册、5 个生命周期钩子顺序、钩子参数与 binding 字段解析,以及函数简写与对象字面量传值。
学完这一章,你能够
- 核对全局与局部自定义指令注册、5 个生命周期钩子顺序、钩子参数与 binding 字段解析,以及函数简写与对象字面量传值。
全局与局部自定义指令(v-focus)
除 `v-model`、`v-show` 等内置核心指令外,Vue 2 支持通过 `Vue.directive(name, definition)` 注册全局自定义指令,或通过实例选项 `directives: { ... }` 注册局部指令,用于封装底层 DOM 操作。以自动聚焦 `v-focus` 为例,在 `inserted` 钩子中调用 `el.focus()` 可在元素挂载后立即获得焦点。本站离线 Chromium 实测全局与局部挂载两个 `<input>` 时,`document.activeElement.id` 分别精确指向 `inp-global` 与 `inp-local`。
自定义指令的 5 个生命周期钩子
指令定义对象提供 5 个可选钩子函数:`bind` 在指令首次绑定到元素时调用一次,适合一次性初始化;`inserted` 在被绑定元素插入父节点时调用(父节点存在即可,不必已进入 document);`update` 在所在组件 VNode 更新时调用(不论绑定值是否改变,可对比新旧值跳过无效 DOM 操作);`componentUpdated` 在所在组件及其子 VNode 全部更新完成后调用;`unbind` 在指令与元素解绑时调用一次。本站离线 Chromium 完整模拟挂载、更新与移除周期,录得严格顺序 `['bind', 'inserted', 'update', 'componentUpdated', 'unbind']`,且 `update` 收到 `oldValue = 1`、`value = 2` 及不同版本的 `vnode`/`oldVnode`。
钩子函数参数、函数简写与对象字面量
钩子依次接收 `el`(绑定 DOM 元素)、`binding`(含不含 `v-` 前缀的 `name`、求值后的 `value` 如 `1 + 1` 得 `2`、仅在 `update`/`componentUpdated` 可用的 `oldValue`、原始表达式字符串 `expression`、冒号参数 `arg` 如 `v-my-directive:foo` 得 `"foo"`、修饰符键值对象 `modifiers` 如 `.foo.bar` 得 `{ foo: true, bar: true }`)、`vnode` 及仅更新阶段可用的 `oldVnode`。本站离线 Chromium 将 `v-demo:hello.a.b="message"` 对应的 `binding` 与 `Object.keys(vnode)` 渲染到页面,6 行输出全部与解析字段一致。
若仅关心 `bind` 与 `update` 时的相同逻辑,可直接传入简写函数 `Vue.directive(name, function (el, binding) { ... })`;指令值支持任意合法 JavaScript 表达式,包括对象字面量(如 `{ color: 'green', text: '...' }`)。本站离线 Chromium 实测先传入绿色背景对象测得计算背景色 `rgb(0, 128, 0)`,更新为蓝色对象后文本与背景色同步切换为 `rgb(0, 0, 255)`。
离线 Chromium 验证自定义指令聚焦、钩子顺序与参数解析
"""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()
- 核对全局/局部 v-focus 聚焦结果、5 钩子调用顺序、binding 全部属性渲染及函数简写接收对象字面量的实时样式更新。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:d7ab1dc044f5c28bd02b7767082b8f33f4cbbdac3e53956b3d2a25cecf152e40
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:0a28c805b465f71829d8c9b3d08123a8782996264d4061cd3c785da8680cabd0
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么自动聚焦指令 `v-focus` 通常写在 `inserted` 钩子而不是 `bind` 钩子中?
展开参考解答
因为在 `bind` 触发时元素尚未插入父 DOM 节点,此时调用 `el.focus()` 不会生效;而 `inserted` 在元素插入父节点后执行,可确保聚焦操作正确作用在已挂载的输入控件上。