SoFunction
Updated on 2025-04-11

Talk about some understanding of mixin in vue

Vue provides a hybrid mechanism - mixins, which is used to more efficiently implement the reuse of component content. At first I thought this seemed to be no different from the component. . Later I found out that I was wrong. Let’s take a look at the difference between mixins and introducing components in ordinary cases?

After reference, a component is equivalent to opening up a separate space in the parent component to perform corresponding operations based on the values ​​from the parent component props. In essence, the two are clearly distinct and relatively independent.

After introducing the component, mixins merges the contents inside the component such as data, method and other attributes with the corresponding content of the parent component. It is equivalent to that after the introduction, various attribute methods of the parent component have been expanded.

Simple component reference:

Parent Component + Child Component >>> Parent Component + Child Component

     mixins:

Parent component + child component >>> new parent component

It is worth noting that when using mixins, the parent component and the child component have various attribute methods in the child component at the same time, but this does not mean that they share and process these variables at the same time. There will be no communication between the two except mergers. When I first saw mixins, I seemed to see a downward data sharing solution similar to vuex, and I was very excited.

Let me introduce it to you belowMixin in Vue

1. What is mixin

A mixin file is an object that can contain any component of a vue component. It is a very flexible way to distribute Vue component reusable functions. When a mixin is used by a component, all attributes/methods in minxin will be mixed with the attributes/methods in the component.

2. Use mixin

In the Vue component, there can be a mixins attribute, and the value type of this attribute is an array. Introduce mixin as elements of mixins array mixins: [mixin]

Component A applies mixin. The properties of the two such as methods, components and directives will be mixed into the same object. If methods, components and directives have attributes with the same name, the mixin will be ignored. The hook function with the same name will form an array and will be called, and the hook function of the mixin will be called first before the hook function of the component.

Summarize

The above is the vue mixin introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!