What are the application scenarios for the understanding of Vue's mixin?
what is mixin
official definition
mixin
(mixins), which provide a very flexible way to distribute reusable functionality in Vue
components .
The essence is actually an js
object, which can contain any function options in our components, such as data
, components
, methods
, created
, computed
etc.
We only need to pass the common function into mixins
the option , and when the component uses mixins
the object, the options of all mixins
objects will be mixed into the options of the component itself.
Precautions
When the component has mixin
the same options as the object, the option of the component will be overwritten when the recursive merge is mixin
performed
But if the same option is a life cycle hook, it will be merged into an array, the hook will be executed first mixin
, and then the hook of the component will be executed
scenes to be used
In daily development, we often encounter the same or similar codes that need to be used in different components, and the functions of these codes are relatively independent
Vue
At this time, mixin
the same or similar code can be proposed through the function
example
Define a modal
pop-up window component, which is used isShowing
to control the display internally
const Modal = {
template: '#modal',
data() {
return {
isShowing: false
}
},
methods: {
toggleShow() {
this.isShowing = !this.isShowing;
}
}
}
Define a tooltip
prompt box, which is internally isShowing
controlled by
const Tooltip = {
template: '#tooltip',
data() {
return {
isShowing: false
}
},
methods: {
toggleShow() {
this.isShowing = !this.isShowing;
}
}
}
By observing the above two components, it is found that the logic of the two is the same, and the code control display is also the same, which mixin
will come in handy at this time
First extract the common code, write amixin
const toggle = {
data() {
return {
isShowing: false
}
},
methods: {
toggleShow() {
this.isShowing = !this.isShowing;
}
}
}
In use of the two components, only need to introducemixin
const Modal = {
template: '#modal',
mixins: [toggle]
};
const Tooltip = {
template: '#tooltip',
mixins: [toggle]
}
Through the above small example, let us know that Mixin
it is so interesting, convenient and practical to encapsulate some reusable functions