Vue Mix
Mixins provide a very flexible way to distribute reusable functionality in Vue components. A mixin object can contain arbitrary component options. When a component uses a mixin object, all options for the mixin object will be “mixed” into the options of the component itself.
First paste an official tutorial and my understanding of this tutorial
1 | Define a mixed object |
In this sample code, you first define a mix that includes a created and a method, and then use mixins to import the mix in the component that needs to use the code, so that you can use the mix in the component everything in it.
This is actually a bit like inheritance in Java. Mixing is similar to a parent class, and a component is equivalent to a subclass. The component has all the behaviors of mixing, including function, lifecycle, event monitoring, etc. At the same time, we can rewrite the content in the component.
Option merge
When components and mixed objects contain options with the same name, these options will be “merged” in an appropriate manner.
For example, data objects will perform recursion merging internally and prioritize component data in case of conflict.
1 | var mixin = { |
The hook functions with the same name will be merged into an array, so they will all be called. Also, the hook of the mixed object will be called before the component itself hooks.
1 | var mixin = { |
Options whose value is an object, such as’methods’, ‘components’, and’directives’, will be merged into the same object. When the key names of the two objects conflict, the Attribute - Value Pair of the component object is taken.
1 | var mixin = { |
Global mixing
Mixing can also be registered globally. Use caution when using it! Once global mixing is used, it will affect every Vue instance created after **. When used properly, this can be used to inject processing logic into custom options.
1 | //Inject a processor for the custom option'myOption '. |
extend/component/mixin/extends
The same example from the beginning, but to avoid confusion, our current object name is not myMixin, but myOption.
new
New Vue (myOption): actually instantiates a component
Vue.component is a method for registering or obtaining global components, which means that the extension instance constructor generated by Vue.extend is registered as a component, which can be used in all components that are later than the component registration, such as:
1 | Vue.component('global-component', Vue.extend(myOption)); |
extend
1 | let MyComponent = Vue.extend(myOption); |
mixins
The rules for merging are the same as for extending
1 | new Vue({ |
extends
This is similar to mixins, except that the options of the component itself will have higher priority than the source component to be extended. Also extends accepts an object instead of an array.
1 | new Vue({ |
Priority
extend > extends > mixins
Reference article: