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

在离线 Chromium 中验证混入复用、data 浅合并、钩子顺序、methods 冲突与全局混入

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-mixins.py
explore-mixins.py202 行
"""Offline Playwright Chromium lab for Vue 3 Ch 26: mixins & option merge strategies."""
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 Mixins Lab</title>
</head>
<body>
  <div id="out"></div>
<script>
// Offline Vue 3 options merge & mixin engine
function createMixinApp(rootComponent) {
  const globalMixins = [];

  function mergeOptions(compOptions) {
    const chain = [...globalMixins, ...(compOptions.mixins || []), compOptions];
    const mergedData = {};
    const mergedMethods = {};
    const createdHooks = [];
    const customOptions = {};

    for (const opt of chain) {
      if (typeof opt.data === 'function') {
        Object.assign(mergedData, opt.data()); // shallow merge, later (component) wins
      }
      if (opt.methods) {
        Object.assign(mergedMethods, opt.methods); // object merge, component wins
      }
      if (typeof opt.created === 'function') {
        createdHooks.push(opt.created); // hook array: global -> local mixin -> component
      }
      for (const [k, v] of Object.entries(opt)) {
        if (!['data', 'methods', 'created', 'mixins'].includes(k)) {
          customOptions[k] = v;
        }
      }
    }
    return { mergedData, mergedMethods, createdHooks, customOptions };
  }

  return {
    mixin(m) {
      globalMixins.push(m);
      return this;
    },
    mount(comp = rootComponent) {
      const { mergedData, mergedMethods, createdHooks, customOptions } = mergeOptions(comp);
      const vm = {
        $data: mergedData,
        $options: customOptions
      };
      for (const [k, v] of Object.entries(mergedData)) {
        Object.defineProperty(vm, k, {
          enumerable: true,
          get: () => vm.$data[k],
          set: (val) => { vm.$data[k] = val; }
        });
      }
      for (const [k, fn] of Object.entries(mergedMethods)) {
        vm[k] = fn.bind(vm);
      }
      for (const hook of createdHooks) {
        hook.call(vm);
      }
      return vm;
    }
  };
}

window.runMixinTests = function () {
  // Case 1: Basic mixin reuse
  const logs1 = [];
  const basicMixin = {
    created() { this.hello(); },
    methods: {
      hello() { logs1.push('hello-from-mixin'); }
    }
  };
  createMixinApp({ mixins: [basicMixin] }).mount();

  // Case 2: data shallow merge (component priority)
  const dataMixin = {
    data() {
      return { message: 'hello', foo: 'abc', nested: { a: 1 } };
    }
  };
  let dataSnap = null;
  createMixinApp({
    mixins: [dataMixin],
    data() {
      return { message: 'goodbye', bar: 'def' };
    },
    created() {
      dataSnap = JSON.parse(JSON.stringify(this.$data));
    }
  }).mount();

  // Case 3: lifecycle hook array order + methods conflict resolution
  const hookOrder = [];
  const methodOutputs = [];
  const conflictMixin = {
    created() { hookOrder.push('mixin-created'); },
    methods: {
      foo() { methodOutputs.push('foo'); },
      conflicting() { methodOutputs.push('from mixin'); }
    }
  };
  const vm3 = createMixinApp({
    mixins: [conflictMixin],
    created() { hookOrder.push('component-created'); },
    methods: {
      bar() { methodOutputs.push('bar'); },
      conflicting() { methodOutputs.push('from self'); }
    }
  }).mount();
  vm3.foo();
  vm3.bar();
  vm3.conflicting();

  // Case 4: Global mixin affecting all subsequent instances + custom option
  const globalLogs = [];
  const app4 = createMixinApp({ myOption: 'hello-root!' });
  app4.mixin({
    created() {
      const myOption = this.$options.myOption;
      if (myOption) globalLogs.push(myOption);
    }
  });
  app4.mount();
  app4.mount({ myOption: 'hello-child!' });
  app4.mount({}); // no myOption -> ignored cleanly

  const outEl = document.getElementById('out');
  outEl.textContent = globalLogs.join('|');

  return {
    case1: { logs: logs1 },
    case2: { merged_data: dataSnap },
    case3: { hook_order: hookOrder, method_outputs: methodOutputs },
    case4: { global_logs: globalLogs, dom_text: outEl.textContent }
  };
};
</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.runMixinTests()")
        browser.close()

    expected = {
        "basic_mixin_reuse": {"logs": ["hello-from-mixin"]},
        "data_shallow_merge_and_component_priority": {
            "merged_data": {
                "message": "goodbye",
                "foo": "abc",
                "nested": {"a": 1},
                "bar": "def",
            }
        },
        "hooks_array_order_and_methods_override": {
            "hook_order": ["mixin-created", "component-created"],
            "method_outputs": ["foo", "bar", "from self"],
        },
        "global_mixin_and_custom_option": {
            "global_logs": ["hello-root!", "hello-child!"],
            "dom_text": "hello-root!|hello-child!",
        },
    }
    mapping = [
        ("basic_mixin_reuse", out["case1"]),
        ("data_shallow_merge_and_component_priority", out["case2"]),
        ("hooks_array_order_and_methods_override", out["case3"]),
        ("global_mixin_and_custom_option", 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-mixins-lab/explore-mixins.py

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

下载课程关联工程包:Vue3

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

下载课程关联工程包:Vue3

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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