蓝色天空网mbsky.com · 知识 · 实践 · 创造Vue3 · 本地阅读预览
教程 / 前端开发 / Vue3

Vue3 自定义指令

解析 Vue 3 全局与局部自定义指令注册、7 个生命周期钩子执行顺序、el/binding/vnode/prevVnode 参数详解及函数简写与对象字面量传值,并附 Chromium 实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

全局与局部自定义指令注册

除内置的 `v-model`、`v-show` 等核心指令外,Vue 3 允许开发者注册自定义指令以复用底层 DOM 操作逻辑。通过 `app.directive('focus', { mounted(el) { el.focus() } })` 可注册全局指令,模板中使用 `v-focus` 即可在元素挂载后自动获得焦点;只传指令名 `app.directive('focus')` 时则作为 getter 返回已注册的指令定义。

若指令仅需在单个组件内生效,可在组件选项的 `directives: { focus: { mounted(el) { el.focus() } } }` 中局部注册(在 `<script setup>` 中任何以 `v` 开头且符合驼峰命名的变量如 `vFocus` 也会自动作为局部指令识别)。本站离线 Chromium 实测:全局与局部 `v-focus` 挂载后,`document.activeElement.id` 依次精确指向 `global-focus` 与 `local-focus`。

自定义指令的 7 个生命周期钩子

Vue 3 将自定义指令钩子名与组件生命周期对齐,共提供 7 个可选钩子:`created`(绑定元素的 attribute 或事件监听器应用前调用)、`beforeMount`(指令首次绑定到元素且在父组件挂载前调用)、`mounted`(绑定元素及父组件挂载完成后调用)、`beforeUpdate`(包含组件的 VNode 更新前调用)、`updated`(包含组件及其子组件的 VNode 更新后调用)、`beforeUnmount`(父组件卸载前调用一次)与 `unmounted`(指令解绑且父组件卸载后调用一次)。本站离线 Chromium 实测完整挂载-更新-卸载周期,钩子严格按 `['created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeUnmount', 'unmounted']` 顺序触发。

钩子函数参数详解

每个指令钩子最多接收 4 个参数:第一参数 `el` 为指令绑定的真实 DOM 元素;第二参数 `binding` 是包含上下文信息的对象,涵盖 `instance`(使用该指令的组件实例)、`value`(传递给指令的求值结果,如 `v-my-directive="1 + 1"` 得到 `2`)、`oldValue`(更新前的值,仅在 `beforeUpdate` 与 `updated` 可用)、`arg`(指令参数,如 `v-my-directive:foo` 中为 `'foo'`)、`modifiers`(修饰符对象,如 `.foo.bar` 对应 `{ foo: true, bar: true }`)以及 `dir`(注册指令时传入的定义对象本身)。

第三参数 `vnode` 代表对应真实 DOM 元素的虚拟节点蓝图;第四参数 `prevNode`(官方文档亦称 `prevVnode`)为更新前的上一个虚拟节点,同样仅在 `beforeUpdate` 与 `updated` 中可用。本站离线 Chromium 实测 `v-inspect:foo.foo.bar`:初始挂载时 `value=2`、`oldValue` 为 `undefined`、`prevVnode` 为 `null`、`arg="foo"`、`modifiers={foo:true, bar:true}`;更新为 `3` 后,`updated` 钩子精确收到 `value=3`、`oldValue=2` 及 `prevVnode.value=2`。

函数简写与对象字面量传值

当只需在 `mounted` 和 `updated` 时执行相同 DOM 更新而不关心其他钩子时,可直接向 `app.directive('badge', (el, binding) => { ... })` 传入一个函数作为简写(注意 Vue 2 中的 `Vue.directive(...)` 与 `new Vue({ el })` 在 Vue 3 中已统一迁移为应用实例方法 `app.directive(...)` 与 `createApp(...).mount(...)`)。此外,指令值支持任意合法 JavaScript 表达式,包括对象字面量 `{ color: 'green', text: '...' }`。实测函数简写指令在挂载与更新阶段共触发 `2` 次,DOM 文本与计算背景色从 `Vue3 初始标签`/`rgb(0, 128, 0)` 平滑更新为 `Vue3 更新标签`/`rgb(0, 0, 255)`。

在离线 Chromium 中验证自定义指令聚焦、7 钩子顺序、binding/vnode 参数与函数简写

python · 阅读源码
"""Offline Playwright Chromium lab for Vue 3 Ch 24: custom directives & lifecycle hooks."""
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 Custom Directives Lab</title>
</head>
<body>
  <div id="mount-root"></div>
<script>
// Offline Vue 3 custom directive runtime kernel
function createMiniApp() {
  const globalDirectives = Object.create(null);
  return {
    directive(name, def) {
      if (def === undefined) return globalDirectives[name];
      globalDirectives[name] = typeof def === 'function' ? { mounted: def, updated: def } : def;
      return this;
    },
    mountNode({ container, tag, id, localDirectives = {}, directiveName, arg, modifiers = {}, initialValue }) {
      const dir = localDirectives[directiveName] || globalDirectives[directiveName];
      const normDir = typeof dir === 'function' ? { mounted: dir, updated: dir } : dir;
      const instance = { uid: id };
      const el = document.createElement(tag);
      el.id = id;
      let vnode = { tag, props: { id }, value: initialValue };
      let currentValue = initialValue;

      const makeBinding = (oldVal) => ({
        instance,
        value: currentValue,
        oldValue: oldVal,
        arg,
        modifiers,
        dir: normDir
      });

      if (normDir.created) normDir.created(el, makeBinding(undefined), vnode, null);
      if (normDir.beforeMount) normDir.beforeMount(el, makeBinding(undefined), vnode, null);
      container.appendChild(el);
      if (normDir.mounted) normDir.mounted(el, makeBinding(undefined), vnode, null);

      return {
        el,
        update(nextValue) {
          const prevVnode = vnode;
          const oldVal = currentValue;
          currentValue = nextValue;
          vnode = { tag, props: { id }, value: nextValue };
          if (normDir.beforeUpdate) normDir.beforeUpdate(el, makeBinding(oldVal), vnode, prevVnode);
          if (normDir.updated) normDir.updated(el, makeBinding(oldVal), vnode, prevVnode);
        },
        unmount() {
          if (normDir.beforeUnmount) normDir.beforeUnmount(el, makeBinding(currentValue), vnode, null);
          el.remove();
          if (normDir.unmounted) normDir.unmounted(el, makeBinding(currentValue), vnode, null);
        }
      };
    }
  };
}

window.runDirectiveTests = function () {
  const root = document.getElementById('mount-root');
  const app = createMiniApp();

  // Case 1: Global & local v-focus
  app.directive('focus', {
    mounted(el) { el.focus(); }
  });
  const getterHasMounted = typeof app.directive('focus').mounted === 'function';
  app.mountNode({ container: root, tag: 'input', id: 'global-focus', directiveName: 'focus' });
  const activeAfterGlobal = document.activeElement.id;

  app.mountNode({
    container: root,
    tag: 'input',
    id: 'local-focus',
    localDirectives: { focusLocal: { mounted(el) { el.focus(); } } },
    directiveName: 'focusLocal'
  });
  const activeAfterLocal = document.activeElement.id;

  // Case 2: All 7 Vue 3 directive lifecycle hooks in order
  const hooksLog = [];
  app.directive('trace', {
    created() { hooksLog.push('created'); },
    beforeMount() { hooksLog.push('beforeMount'); },
    mounted() { hooksLog.push('mounted'); },
    beforeUpdate() { hooksLog.push('beforeUpdate'); },
    updated() { hooksLog.push('updated'); },
    beforeUnmount() { hooksLog.push('beforeUnmount'); },
    unmounted() { hooksLog.push('unmounted'); }
  });
  const handle2 = app.mountNode({
    container: root, tag: 'div', id: 'trace-box', directiveName: 'trace', initialValue: 1
  });
  handle2.update(2);
  handle2.unmount();

  // Case 3: binding properties + vnode / prevVnode
  const snapshots = [];
  const inspectDir = {
    mounted(el, binding, vnode, prevVnode) {
      snapshots.push({
        hook: 'mounted',
        uid: binding.instance.uid,
        value: binding.value,
        oldValueIsUndef: binding.oldValue === undefined,
        arg: binding.arg,
        modifiers: binding.modifiers,
        dirHasMounted: typeof binding.dir.mounted === 'function',
        vnodeTag: vnode.tag,
        prevVnodeIsNull: prevVnode === null
      });
    },
    updated(el, binding, vnode, prevVnode) {
      snapshots.push({
        hook: 'updated',
        value: binding.value,
        oldValue: binding.oldValue,
        arg: binding.arg,
        modifiers: binding.modifiers,
        prevVnodeVal: prevVnode.value,
        vnodeVal: vnode.value
      });
    }
  };
  app.directive('inspect', inspectDir);
  const handle3 = app.mountNode({
    container: root,
    tag: 'div',
    id: 'inspect-box',
    directiveName: 'inspect',
    arg: 'foo',
    modifiers: { foo: true, bar: true },
    initialValue: 2
  });
  handle3.update(3);

  // Case 4: Function shorthand (mounted + updated) with object literal
  let fnCalls = 0;
  app.directive('badge', (el, binding) => {
    fnCalls++;
    el.textContent = binding.value.text;
    el.style.backgroundColor = binding.value.color;
  });
  const handle4 = app.mountNode({
    container: root,
    tag: 'div',
    id: 'badge-box',
    directiveName: 'badge',
    initialValue: { color: 'green', text: 'Vue3 初始标签' }
  });
  const badgeMountedText = handle4.el.textContent;
  const badgeMountedBg = getComputedStyle(handle4.el).backgroundColor;
  handle4.update({ color: 'blue', text: 'Vue3 更新标签' });
  const badgeUpdatedText = handle4.el.textContent;
  const badgeUpdatedBg = getComputedStyle(handle4.el).backgroundColor;

  return {
    case1: {
      getter_has_mounted: getterHasMounted,
      active_after_global: activeAfterGlobal,
      active_after_local: activeAfterLocal
    },
    case2: { hooks_order: hooksLog },
    case3: { mounted: snapshots[0], updated: snapshots[1] },
    case4: {
      fn_calls: fnCalls,
      mounted_text: badgeMountedText,
      mounted_bg: badgeMountedBg,
      updated_text: badgeUpdatedText,
      updated_bg: badgeUpdatedBg
    }
  };
};
</script>
</body>
</html>
"""


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)
        out = page.evaluate("window.runDirectiveTests()")
        browser.close()

    expected = {
        "global_and_local_focus_directive": {
            "getter_has_mounted": True,
            "active_after_global": "global-focus",
            "active_after_local": "local-focus",
        },
        "directive_lifecycle_hooks_order": {
            "hooks_order": [
                "created",
                "beforeMount",
                "mounted",
                "beforeUpdate",
                "updated",
                "beforeUnmount",
                "unmounted",
            ]
        },
        "binding_object_and_vnode_args": {
            "mounted": {
                "hook": "mounted",
                "uid": "inspect-box",
                "value": 2,
                "oldValueIsUndef": True,
                "arg": "foo",
                "modifiers": {"foo": True, "bar": True},
                "dirHasMounted": True,
                "vnodeTag": "div",
                "prevVnodeIsNull": True,
            },
            "updated": {
                "hook": "updated",
                "value": 3,
                "oldValue": 2,
                "arg": "foo",
                "modifiers": {"foo": True, "bar": True},
                "prevVnodeVal": 2,
                "vnodeVal": 3,
            },
        },
        "function_shorthand_and_object_literal": {
            "fn_calls": 2,
            "mounted_text": "Vue3 初始标签",
            "mounted_bg": "rgb(0, 128, 0)",
            "updated_text": "Vue3 更新标签",
            "updated_bg": "rgb(0, 0, 255)",
        },
    }
    mapping = [
        ("global_and_local_focus_directive", out["case1"]),
        ("directive_lifecycle_hooks_order", out["case2"]),
        ("binding_object_and_vnode_args", out["case3"]),
        ("function_shorthand_and_object_literal", out["case4"]),
    ]
    cases = [
        {"name": name, "expected": expected[name], "actual": actual, "passed": actual == expected[name]}
        for name, actual in mapping
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对全局与局部 v-focus 真实焦点切换、7 个生命周期钩子完整序列、mounted/updated 的 binding 与 prevVnode 差异及函数简写对象字面量样式更新。
在离线 Chromium 中验证自定义指令聚焦、7 钩子顺序、binding/vnode 参数与函数简写

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:9e8af8265f2585d1a9e3a7eca8e373722dd6e65dac160358a30e37a5614dbfb2

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Vue3 自定义指令实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:b4d58fa2691af5168211e96712cc4177b3e6fedbfc6f24888d29083060797197

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

向 app.directive('color', fn) 直接传入函数而非对象时,该函数会在哪些生命周期钩子中执行?oldValue 与 prevVnode 仅在哪些钩子中可用?

展开参考解答

函数简写会在 mounted 和 updated 两个阶段调用;oldValue 与 prevVnode 仅在 beforeUpdate 和 updated 钩子中可用。

规范与官方依据