SoFunction
Updated on 2025-04-13

Detailed explanation of the example of using Mixin in Vue3

Mixin is a code reuse mode in Vue that allows components to be extracted (such as data, methods, lifecycle hooks, etc.) into independent modules and multiplexed in multiple components. Vue 3 retains Mixin support, but its usage scenarios have changed as the Composition API becomes more popular. The following is a detailed analysis:

1. Basic usage

1. Define Mixin

// 
export const myMixin = {
  data() {
    return {
      mixinData: "Data from Mixin",
    };
  },
  methods: {
    mixinMethod() {
      ("Mixin's method");
    },
  },
  created() {
    ("Mixin's created hook");
  },
};

2. Use Mixin

import { myMixin } from "./myMixin";

export default {
  mixins: [myMixin],
  created() {
    ("Created hook for component");
  },
};

Output result:

Mixin's created hook
The created hook for the component

2. Common scenarios

1. Reuse general logic

For example, multiple components require the same data attributes (such as user information), methods (such as logging), or lifecycle logic (such as event listening).

2. Global function injection

Unified functions are added through global Mixin (such as burying point statistics), but they should be used with caution to avoid contaminating all components.

3. Extend third-party components

Modify the default behavior of third-party components by mixing in (such as adding verification logic).

3. Frequently Asked Questions and Solutions

1. Naming conflict

Problem: Vue is overridden by priority when an attribute or method of the same name is defined between a Mixin and a component or a Mixin.

Solution:

  • Unified naming specifications (such as adding mixin_ prefix).
  • Use Composition API to replace (more flexible and conflict-free).

2. The source is unclear

Problem: When multiple Mixins are mixed into components, it is difficult to trace the origin of properties and methods.

Solution:

  • Limits the number of Mixins mixed into a single component.
  • Use TypeScript to enhance type prompts (see below).

3. Responsive data update problem

Problem: Modifying responsive data in Mixin directly can lead to unexpected behavior.

Solution:

  • Modify the data through methods (such as updateData()), rather than assigning values ​​directly.
  • Encapsulate data using reactive or ref (Composition API).

4. TypeScript Support

Problem: Mixin's TypeScript type inference is weak.

Solution:

Use defineComponent and generic enhancement types:

import { defineComponent } from "vue";

export const myMixin = defineComponent({
  data() {
    return {
      mixinData: "data",
    };
  },
});

4. Best Practices

1. Prioritize Composition API

// Use Composables instead of Mixinexport function useLogger() {
  const logMessage = (message) => {
    (message);
  };
  return { logMessage };
}

// Used in componentsimport { useLogger } from "./useLogger";
export default {
  setup() {
    const { logMessage } = useLogger();
    return { logMessage };
  },
};

2. Limit Mixin responsibilities

A Mixin is only responsible for a single function (such as logging, permission verification).

3. Clarify the merger strategy

Lifecycle hook: merge in order of mixing and execute all.

data, methods: The latter of the same name covers the former.

Custom merge policy (advanced):

 = (parent, child) => {
  return (child);
};

5. Mixin vs Composition API

characteristic Mixin Composition API
Code Organization Component-based options Based on logic functions (functional)
Naming conflict It can easily occur None (by naming isolation)
Type support weak Strong (natural support TypeScript)
Maintainability Low (logical dispersion) High (logical concentration)

6. FAQs

Q1: What is the difference between Mixin and extends?

mixins are array-like mixed with multiple logic, extends are inheriting a single component.

Q2: How to detect naming conflicts in Mixin?

In development mode, Vue warns data conflicts, but methods conflicts need to be checked by themselves.

Use ESLint plug-in (such as vue/no-confusing-v-for-v-if) to assist with detection.

Q3: Is global Mixin recommended?

Not recommended unless necessary (such as burying sites throughout the site). Global Mixin affects all components and is difficult to debug.

Summarize

Suitable for Mixin scenarios: simple logic reuse, old project maintenance, needing to mix life cycle hooks.

Recommended alternative: Vue 3's Composition API (more flexible logical reuse with setup + Composables).

By choosing the Mixin or Composition API rationally, you can significantly improve the maintainability and scalability of your code.

The above is the detailed explanation of the example of using Mixin in Vue3. For more information about Mixin in Vue3, please follow my other related articles!