preface

Vue is a progressive JavaScript framework. Its core problem is to solve the problem of view rendering. Other functions can be solved by installing plug-ins.

Vue.use

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    if (installedPlugins.indexOf(plugin) > -1) {
      return this
    }
    
    const args = toArray(arguments.1)
    args.unshift(this)
    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }
    installedPlugins.push(plugin)
    return this}}Copy the code

Vue.use is a global API that takes a function or object as an argument and internally maintains an installedPlugins variable to store installed plug-ins, ensuring that the plug-in procedure can only be called once. Main process:

  • First determine whether the incoming plug-in has been installed and return it if it has
  • Structural parametersargsThat will beVueAdded to theargsThe first position of the
  • Judge pluginsinstallProperty is a function. If it is a function, call the plugin’sinstallmethods
  • Otherwise, the plugin is checked to see if it is a function, and if it is, the plugin itself is called to pass in the constructed arguments
  • Finally, the plug-in is pushed to internally maintainedinstalledPluginsvariable

One optimization point here is that passing the Vue as a parameter to the plug-in, rather than importing Vue from ‘Vue’ in the plug-in, reduces the size of the package.