There are two more advanced static methods mixin and extend in Vue. Next, let’s discuss their respective principles and usage scenarios.
Mixin:
principle:
Let’s take a look at the introduction of the official website:
Parameters: {Object} mixin
usage:
Mixed in can also be used for global registration. Be extra careful when using it! Once global mix-in is used, it will affect each Vue instance created later. This can be used to inject processing logic into custom options when used.
// Inject a processor for the custom option 'myOption'. ({ created: function () { var myOption = this.$ if (myOption) { (myOption) } } }) new Vue({ myOption: 'hello!' }) // => "hello!"
We know that the passed parameter object will be merged to options when initializing the Vue instance. The following is the operation of mixin in the Vue source code.
// src\core\global-api\ export function initMixin (Vue: GlobalAPI) { = function (mixin: Object) { = mergeOptions(, mixin) return this } } // src\core\instance\ function Vue (options) { if (.NODE_ENV !== 'production' && !(this instanceof Vue) ) { warn('Vue is a constructor and should be called with the `new` keyword') } this._init(options) } initMixin(Vue) ... export default Vue
That is, mixin is just an extension of the configuration object we pass when initializing a Vue instance.
Just like the example written in the official website example above, when we execute the method, we pass a configuration object in, and there is a created hook function in the object. Through the source code, we can see that the object passed in will eventually be initing the instance with us.new Vue(options)
This option is merged (through the mergeOptions method in the source code above), and saved on the option.
Use scenarios:
When we need to inject some methods, filters or hooks globally, we can use mixin to do it. For example, we hope that each Vue instance has a print method, and we can do this:
({ methods: { print() { (`I'm a passmixinMethod of injection!`) } } })
Or we want to listen to what stage of the component is loaded, uninstalled, etc., we can do this:
({ mounted() { (`${this.$} component mounted!`) }, destroyed() { (`${this.$} component destroyed!`) } })
If we do not want to mix these configuration options for each component instance, but just individual components, it is best not to use mixin, it may affect the performance of our components.
Extend:
principle:
Let’s take a look at the introduction of the official website:
Parameters: {Object} options
usage:
Using the basic Vue constructor, create a "subclass". A parameter is an object containing component options.
The data option is a special case, please note -()
It must be a function.
Data must be a function to prevent data confusion in each instance and closure application.
<div ></div> // Create a constructorvar Profile = ({ template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>', data: function () { return { firstName: 'Walter', lastName: 'White', alias: 'Heisenberg' } } }) // Create a Profile instance and mount it on an element.new Profile().$mount('#mount-point')
Let’s take a look at the implementation in the source code:
= function (extendOptions: Object): Function { extendOptions = extendOptions || {} const Super = this const SuperId = const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}) if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } const name = || if (.NODE_ENV !== 'production' && name) { validateComponentName(name) } const Sub = function VueComponent (options) { this._init(options) } = () = Sub = cid++ = mergeOptions( , extendOptions ) Sub['super'] = Super // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids calls for each instance created. if () { initProps(Sub) } if () { initComputed(Sub) } // allow further extension/mixin/plugin usage = = = // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function (type) { Sub[type] = Super[type] }) // enable recursive self-lookup if (name) { [name] = Sub } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. = = extendOptions = extend({}, ) // cache constructor cachedCtors[SuperId] = Sub return Sub } }
First of all, we can see that the Sub returned by the extend method is actually a constructor and inherited from Vue, which means that the extend method returns a subclass of Vue.
= () = Sub
These two lines of code actually implement Sub's inheritance to Vue. One line in the source code is
const Super = this
So Super here refers to Vue.
= mergeOptions( , extendOptions )
We noticed that in extend, we will also merge the configuration option passed in and the original options of Vue.
Use scenarios:
When we don't need to mix in some configurations globally, for example, we want to get a component. We can use(),
Can also be used()。
const ChildVue = ({ ...options }) new ChildVue({ ...options })
Note that extend gets a subclass of Vue, that is, the constructor.
the difference:
mixin is to mix options of Vue class. All Vue instance objects have mixed configuration behavior.
extend is to generate a subclass inherited from the Vue class, which will only affect the instance object of this subclass and will not affect the Vue class itself and the instance object of the Vue class.
Summarize
The above is the difference and usage scenarios between mixin and extend in Vue introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!