Mixin provides a very flexible way to distribute reusable functionality in Vue components. A mixin object can contain any component option. When a component uses mixin, all mixin options are “blended” into the component’s own options.

This object is a component. All the contents of export defalut{} except HTML can be mixed into the component, including data, methods and so on.

Then download a source code to see how it works, I am under version 2.6.12!

1. Initialize mixins

The code is simple, and options here refer to parameters such as data and methods in the component to be mixed into the merge. In fact, it mainly relies on the mergeOptions() function to implement

2. MergeOptions () function -merge parameters!

MergeOptions () recursively loops through components and mixins for data, methods, computed, and watch, and takes precedence over components in case of conflicts, whereas mergeFiedld() merges them.

3. At this point we also need to look for strat objects

The strat object contains data, props, methods, computed, and watch, all of which we normally use. How does it combine functions with data

4. MergeDataOrFn () method

Finally, the real method of combining data and functions is mergeData()

5. MergeData () method

In this case, it can be seen that the mergeData method is still a recursive loop of data, methods, computed, watch and other data in the component and the mixin, and compares the parameters of the component and the mixin. If the keys are the same, the parameters of the component are retained. At this point, we understand that after mixing an object, we are doing the work of merging! After the merge, the data and methods in the mixin can be used in the component.

Use:

Note that mixins take precedence over component data or function calls, so that the mixin object data can be merged into the component. Therefore, the loaded data and functions are subject to the loading order of their own components, namely: name > mixin > components > data > watch > computed > created > mounted > methods > updated > destroyed

Finally, I attach my personal understanding of mixins and vuex, mixins and components

Mixins and vuex

Mixins can provide custom variables for multiple components to use, while Vuex is more of a global state management function, which is somewhat the same. Mixins are merged into the parent component itself, and the variables of each component are independent, so the data used to modify mixins within a component is changed separately, which is clearly different from vuEX global state management

A mixin and the component

When a component is introduced, a separate space is created in the parent component for the child component to use, and the two independent components are parallel. Mixins are introduced into the parent component as merged objects to augment the parent component’s data and methods.