使用vue前端框架开发有些时间了,官方文档对于插件开发也有详细的介绍。最近强迫症犯了,老在想为什么vue.use函数执行,要在vue实例化即new vue(options)
之前。解铃还须系铃人,这个问题只能通过看源码解决,于是。。。
先看vue.use做了什么
vue.use = function (plugin: function | object) { //vue构造函数上定义_installedplugins 避免相同的插件注册多次 const installedplugins = (this._installedplugins || (this._installedplugins = [])) // import是单例模式 //所以plugin不论是fuction还是object同一个插件都是同一个 if (installedplugins.indexof(plugin) > -1) { return this } // additional parameters const args = toarray(arguments, 1) // vue作为第一个参数传递给插件 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 // 返回的是this,可以链式调用 }
do:
plugin.install
还是pluginvue.prototype._init中合并options 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 ) ... // 挂载到dom上 if (vm.$options.el) { vm.$mount(vm.$options.el) } }
在new vue(options)
时首先会执行this._init进行初始化,将vue上的属性和options进行合并,然后在进行事件、生命周期等的初始化。beforecreate,created生命周期的hook函数也是在这里进行调用
如果vue.use在new vue()
之后执行,this._init()
时你使用的插件的内容还没有添加到vue.options.components、vue.options.directives、vue.options.filters等属性中。所以新初始化的vue实例中也就没有插件内容
总结
以上所述是小编给大家介绍的vue.use()在new vue() 之前使用的原因浅析,希望对大家有所帮助
如对本文有疑问, 点击进行留言回复!!
2020-07-21 html5如何监听veido的全屏 + css的字体间距 + JS的window.open() + 软技能svn与git
html+css+js适合前端小白的实战全解(超详细)——2048小游戏(二)
在使用@angular/cli创建的angular项目上添加postcss等一系列移动端自适应插件
网友评论