mixin
mixin: The translation is called mixin, some people call it mixin, and the official name is mixin
Function: two components share a configuration (configuration must be the same), the essence is to reuse configuration
Learn how to use and function through case understanding
1 Write a case
Make a request and add a new component. When you click on a student’s name, a pop-up window will display the student’s name. When you click on the school’s name, a pop-up window will display the school’s name.
It works, but it's not good enough
These codes are all the same. It would be better if they can be reused under encapsulation. At this time, they can be mixed in with the help of mixin
2 Create a mixin file
Create a mixin.js file, write it as an object to receive and expose with constants
3 Reference mixins
After creating and writing the corresponding code, you can introduce it in the components you need
4 mix in
After the introduction, you need to add a new configuration item: mixins, its value is an array, which is a bit like props
have a test
5 What can be written in mixin?
As long as it is a property that can be written in the component, the mixin can be written. For example, here I wrote a mount function
Of course, the two components are output twice.
Another example is that I define a data in the mix, which contains x and y respectively
import and use
It is found that there are also mixed x and y in the component
6 Mixins and component precedence
Just defined x in the mix-in, if there is also an x in the component, then whose priority is higher
Through testing, it is found that the priority of components is greater than that of mixing
7 a pit
It has just been verified above that the priority is that the component is greater than the mix-in. To be precise, if the data in data and the methods in the methods conflict, it is true that the priority of the component is greater than the mix-in, but if it is some life cycle hook function, it will be as The priority of mix-ins is greater than that of components, and they are all preserved
8 Global mixins
The examples just now are all local mixins. If you want to achieve global mixins, you can do this
Introduce mix-in and use in main.js, because main.js is the entry point of the program
Writing in this way will add mix-in to all vm and vc, which may lead to performance degradation. You can use it according to your needs and scenarios
9 summary
mixin
Function: The configuration shared by multiple components can be extracted into a mix-in object
- How to use:
- 1 Define a mixin such as: {data(){}}
- 2 Use mixins such as: (1) Global mix Vue.mixin(xxx) (2) mixins:['xxx']