Close read Vue official documentation series 🎉
basis
Mixin refers to mixing logic or functionality into a target component that can be reused across multiple components.
To put it simply, you can equate “mixin object” to the pure logical part of a component (the
A mixin object can contain any component options that are “blended and merged” with the target component’s options in the appropriate way.
Methods and data mixed into objects can be shared but not shared among multiple components.
A simple mixin object:
//src/mixins/sayHelloMixin.js
export default {
data() {
return {
message: 'hello! '}},created() {
console.log(this.message)
}
}
Copy the code
Import sayHelloMixin and pass it into the mixins option of the target component for local registration.
import sayHelloMixin from ".. /mixins/sayHello";
export default {
name:'Hello'.mixins:[sayHelloMixin]
}
Copy the code
Or use vue.extend () to create a whole new component object based on the mixin object.
import sayHelloMixin from ".. /mixins/sayHello";
import Vue from 'vue'
export default Vue.extend({mixins: [sayHelloMixin]})
Copy the code
Option to merge
The rules for mixing objects and target components are as follows:
- The data method recursively merges key-value pairs of the data, and if the keys conflict, uses the data in the component first.
- The hook functions are merged into an array, so they are all called, noting that the intermixed object hooks are executed before the component’s own hooks.
- Component options with an object value are merged, and when object key names conflict, the component object’s key-value pair is taken.
With global
Use the vue.mixin () method to register global mixin objects.
Global blending should be avoided. The focus here is on the execution priority of mixins registered in different ways: component options → locally registered mixins → globally registered mixins
Customize option merge policy
Through the Vue. Config. OptionMergeStrategies. [myOption] can customize with some options in the object with the component objects merge strategy.
Where myOption is a placeholder whose actual name should be the name of the option to merge.
For options with multiple numeric objects, you can use the same merge strategy as methods:
var strategies = Vue.config.optionMergeStrategies
strategies.myOption = strategies.methods
Copy the code
example
Imagine that there are two components, Modal and Tooltip. Although they are different in form, they have the same interaction logic, for example, they both have the function of switching between show and hide.
At this point, with mixed goals and definitions, we can extract reusable functionality into a mixin object.
var toggleMixin = {
data() {
return {
show: false}},methods: {
toggle() {
this.show = !this.show; }}}Copy the code
Then use it in Modal and Tooltip respectively:
<! --Modal.vue-->
export default {
name:'Modal',
mixins:[toggleMixin],
}
<! --Tooltip.vue-->
export default {
name:'Modal',
mixins:[toggleMixin],
}
Copy the code