蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-custom-directive.py
explore-custom-directive.py265 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/vue3-custom-directive-lab/explore-custom-directive.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-custom-directive.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Vue3

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip

下载课程关联工程包:Vue3

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a816.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习