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:
- Check whether the plug-in is registered. The same plug-in is registered only once
- Take the Vue constructor as the first argument and call it as a plug-in registration
- Choose whether to call plugin.install or plugin depending on the form of the plug-in
- 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