The use and attention of minxin in vue

Basic overview of mixins

The explanation in vue is like this, if you feel that the language is boring, you can skip it by yourself~

Mixins: are a very flexible way of distributing reusable functionality in Vue components. Mixins can contain arbitrary component options. When a component uses a mixin, all the options of the mixin will be mixed into the options of the component itself.

Take a chestnut:

  • define a mixin object

  • Mix in the object into the current component

 

Features of mixins

Methods and parameters are not shared among components, and it can be realized with minxin.

1. The parameter num in the mixed object

 The parameter num in component 1 performs +1 operation

 Parameter num in component 2 is not manipulated

 Look at the num values ​​​​output respectively in the two components

As you can see, I changed the value of num in component 1, and the value of num in component 2 is still the initial value mixed into the object

2 Options whose values ​​are objects, such as methods, components, etc., the options will be merged, and the components with key conflicts will override the mixed-in objects

Methods mixed into objects

method in component 

print station output

3 Options whose value is a function, such as created, mounted, etc., will be combined and called, and the hook function in the mixed object is called before the hook function in the component

The console mixed into the object function

 

 console in component function

print station printing

The difference with vuex

After the above example, the difference between them should be obvious~

  • vuex: It is used for state management. The variables defined in it can be used and modified in each component. After modifying the value of this variable in any component, the value of this variable in other components will also be modified accordingly.

  • Mixins: Common variables can be defined and used in each component. After being introduced into the component, each variable is independent of each other, and the modification of the value will not affect each other in the component.

Differences from public components

The same obvious difference is listed again~

  • Component: Introducing a component in the parent component is equivalent to giving an independent space in the parent component for the child component to use, and then passing values ​​according to props, but the two are relatively independent in essence.

  • Mixins: After the component is introduced, it is merged with the objects and methods in the component, which is equivalent to extending the objects and methods of the parent component, which can be understood as forming a new component.

Guess you like

Origin blog.csdn.net/qq_38210427/article/details/130704377