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

Vue3 混入

梳理 Vue 3 混入(mixins)的复用写法、data 浅合并与组件优先规则、生命周期钩子数组顺序、methods 冲突覆盖与 app.mixin 全局混入风险,并附 Chromium 实测。

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

学完这一章,你能够

混入(Mixins)的基本概念与复用方式

混入(Mixins)用于把多个组件共享的选项(如 `data`、`methods`、`computed` 与生命周期钩子)抽离成普通 JavaScript 对象,再通过组件配置项 `mixins: [myMixin]` 合并进目标组件。本站离线 Chromium 实测:在混入对象中定义 `created()` 调用 `this.hello()`,应用挂载后直接执行并记录 `['hello-from-mixin']`。

选项合并策略:数据、钩子与对象型选项

当组件自身与混入对象存在同名选项时,Vue 3 按选项类型采用不同合并策略。对于 `data()` 返回的数据对象,Vue 执行浅合并(仅合并顶层属性),出现同名键时以组件自身数据优先。实测混入返回 `{ message: 'hello', foo: 'abc', nested: { a: 1 } }`、组件返回 `{ message: 'goodbye', bar: 'def' }` 时,最终 `this.$data` 为 `{"message":"goodbye","foo":"abc","nested":{"a":1},"bar":"def"}`。

对于同名生命周期钩子(如 `created`),Vue 会将其合并成一个执行数组并全部调用,且混入对象的钩子永远先于组件自身的钩子执行。实测钩子触发顺序精确为 `['mixin-created', 'component-created']`。

对于值为对象的选项(例如 `methods`、`components` 和 `directives`),Vue 会合并为同一个对象;若键名冲突则保留组件自身的键值对。实测混入提供 `foo()` 与 `conflicting()`、组件提供 `bar()` 与 `conflicting()`,依次调用 `vm.foo()`、`vm.bar()`、`vm.conflicting()` 输出 `['foo', 'bar', 'from self']`。

全局混入(app.mixin)与 Vue 3 替代建议

通过应用实例方法 `app.mixin({...})` 可注册全局混入,它会影响该应用下随后创建的每一个组件实例(包含第三方组件),因此常仅用于插件或读取自定义选项(如 `this.$options.myOption`)。实测对含不同 `myOption` 的根/子实例与无该选项的第三实例分别挂载,全局混入自动处理前两者并输出 `hello-root!|hello-child!`。工程上必须谨慎使用全局混入,在 Vue 3 中更推荐使用组合式函数(Composables)替代混入,以避免命名冲突与属性来源不透明问题。

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 核对基础混入调用、data 顶层浅合并组件优先、mixin created 先于组件 created、methods 同名由组件覆盖及 app.mixin 读取 $options.myOption。
在离线 Chromium 中验证混入复用、data 浅合并、钩子顺序、methods 冲突与全局混入

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

当前源码 SHA256:4fc0720d8e56b6aa641502962aeda73bfca1dafc74593d135e54168fe10c121d

下载本站示例源码

本地运行

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

下载Vue3 混入实验

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

ZIP SHA256:3fa2cfe72ba24b954f8ce9323bc37e2eb87df936588b3962e1d5668bfe5d28c7

常见错误与边界

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

练习与解答

当组件与混入同时定义了 data、created 与 methods 里的同名项时,Vue 3 的合并结果分别是什么?

展开参考解答

data 顶层浅合并且同名键取组件值;created 合并为数组且混入钩子先于组件钩子执行;methods 合并为同一对象且同名方法取组件定义。

规范与官方依据