在Vue中引入使用第三方库通常我们都会采用import的形式引入进来,但是有的组件在引入之后又做了Vue.use()操作,有的组件引入进来又进行了Vue.prototype.$something = something,那么它们之间有什么联系呢?
1.
Vue.prototype.$axios = axios
//其实是在Vue原型上增加了一个$axios,通过我们会在全局注册这个方法,然后在周后的文件中都可以通过$axios直接来使用axios
2.
通过全局方法 Vue.use() 使用插件,Vue.use 会自动阻止多次注册相同插件,它需要在你调用 new Vue() 启动应用之前完成。
Vue.use() 方法至少传入一个参数,该参数类型必须是 Object 或 Function,如果是 Object 那么这个 Object 需要定义一个 install 方法,如果是 Function 那么这个函数就被当做 install 方法。在 Vue.use() 执行时 install 会默认执行。
Vue.use的源码逻辑:(只能Object 或 Function)
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
}
}