Using the Vue front-end framework for some time, the official documentation for plug-in development is also detailed. Vue. Use is executed before new Vue(options) is instantiated. The solution to the bell must be tied, this problem can only be solved by looking at the source code, so…

What does Vue.use do first

Vue.use = function (plugin: Function | Object) {
    // Define _installedPlugins on the Vue constructor to avoid registering the same plug-in multiple times
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    // import is a singleton
    // Plugin is the same as the function or Object
    if (installedPlugins.indexOf(plugin) > - 1) {
      return this
    }

    // additional parameters
    const args = toArray(arguments.1)
    // Vue is passed to the plug-in as the first argument
    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 // Returns this, which can be chained
  }
Copy the code

do:

  1. Check whether the plug-in is registered. The same plug-in is registered only once
  2. Take the Vue constructor as the first argument and call it as a plug-in registration
  3. Choose whether to call plugin.install or plugin depending on the form of the plug-in
  4. Stores registered plug-ins to verify that the plug-in is registered

Combine options in vue.prototype. _init

 Vue.prototype._init = function (options? : Object) {
    const vm: Component = this
    // a uid
    vm._uid = uid++
    let startTag, endTag
    ...
    vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
     ...
     // Mount to dom
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
}
Copy the code

When new Vue(options) is initialized, this._init will be executed first, combining the attributes and options on the Vue, and then initialization of events, life cycles, etc. The beforeCreate,created lifecycle hook functions are also called from here

If vue.use is executed after new Vue(), The contents of the plug-in you use for this._init() have not been added to the Vue.options.components, vue.options.directives, vue.options.options. Filters, etc. So there is no plug-in content in the newly initialized Vue instance