Use (plugin, arguments)

use<T>(plugin: PluginObject<T> | PluginFunction<T>, options? : T): void; use(plugin: PluginObject<any> | PluginFunction<any>, ... options: any[]): void;Copy the code

As you can see from the above code, the first plugin parameter plugin accepts an obj or fn, and the second parameter optionally accepts an array (what is the generic

export type PluginFunction<T> = (Vue: typeof _Vue, options? : T) => void; export interface PluginObject<T> { install: PluginFunction<T>; [key: string]: any; }Copy the code

A PluginObject must have a install method if it is an object, and a PluginFunction must return no value if it is a function.

function initUse (Vue)

Now that the input is defined, let’s see what happens to use, we found the initUse method in initGlobalAPI.

Function initUse (Vue) {Vue. Use = function (plugin) { installedPlugins var installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); If (installedplugins.indexof (plugin) > -1) {return this} // Additional parameters var args = toArray(arguments, 1); // Add this args.unshift(this) to the header; If (typeof plugin.install === 'function') {typeof plugin.install === 'function') { Change this to plugin plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') {if (typeof plugin === 'function') {if (typeof plugin === 'function') {if (typeof plugin === 'function'); } // Add plugins installedplugins.push (plugin); return this }; }Copy the code

extension

So we’ve seen the toArray method so let’s look at it

/**
 * Convert an Array-like object to a real Array.
 */
function toArray (list, start) {
  start = start || 0;
  var i = list.length - start;
  var ret = new Array(i);
  while (i--) {
    ret[i] = list[i + start];
  }
  return ret
}
Copy the code

As you can see from the comment, this is a method to convert an array of classes into a true array. Here you can imagine how to convert in ES6.

conclusion

Ok, after the analysis of use today, we see that the process of use is:

  • Verify that the plug-in is registered first. If it exists, it will be registered only once.

  • Unregistered plug-ins to determine the type of plug-in. If it is an object, you must have the install method, if it is a function directly inserted. (Remember to change this to oh ~)

  • Finally add it to the list of registered plug-ins.


If this article is useful, feel free to comment, like, and follow.

I’m Leo: I wish you all a promotion and a raise soon.