前言:希望通过这篇文章,让你简单了解Vue.use的源码做了什么事情。只有十几二十行源码,不看白不看。
1. vue.use方法源码
路径:node_modules/vue/src/core/global-api/use.ts
import type { GlobalAPI } from 'types/global-api'
import { toArray, isFunction } from '../util/index'
export function initUse(Vue: GlobalAPI) {
Vue.use = function (plugin: Function | any) {
const installedPlugins =
this._installedPlugins || (this._installedPlugins = [])
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
const args = toArray(arguments, 1)
args.unshift(this)
if (isFunction(plugin.install)) {
plugin.install.apply(plugin, args)
} else if (isFunction(plugin)) {
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
}
1. Vue.use干嘛用的?
一般是用来注册 第三方的库用的,里面可以接受函数、对象。如果接受函数就直接调用,如果接收的是对象,就会去里面找install方法,再去调用他
2. 判断插件是否注册
……上面也暂时删除
export function initUse(Vue: GlobalAPI) {
Vue.use = function (plugin: Function | any) {
const installedPlugins =
this._installedPlugins || (this._installedPlugins = [])
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
……中间部分暂时删去
installedPlugins.push(plugin)
return this
}
}
-
use方法,接受参数plugin,值可以是函数也可以是任意类型。
-
里面的installedPlugins是一个数组,是库的集合
-
判断要注册的这个库,是否已经存在了,利用indexOf方法进行判断,如果已经存在了,就直接return this,this在Vue.use方法里面,所以this指向的是Vue实例
-
如果这个库不存在,就插入到installedPlugins这个数组里面去
3. use如何处理传递进来的参数
import type { GlobalAPI } from 'types/global-api'
import { toArray, isFunction } from '../util/index'
export function initUse(Vue: GlobalAPI) {
Vue.use = function (plugin: Function | any) {
const installedPlugins =
this._installedPlugins || (this._installedPlugins = [])
if (installedPlugins.indexOf(plugin) > -1) {
return this
// additional parameters
+ const args = toArray(arguments, 1)
+ args.unshift(this)
+ if (isFunction(plugin.install)) {
+ plugin.install.apply(plugin, args)
+ } else if (isFunction(plugin)) {
+ plugin.apply(null, args)
+ }
installedPlugins.push(plugin)
return this
}
}
-
把传递进来的参数转化为数组,去掉第一个参数
-
往开头又插入一个参数,就是this,就是Vue实例。
这一点很重要,因为创建VueRouter类的时候,第一个参数就是Vue实例,我们可以挂载$router对象,而Vue实例就是这里传递进来的。 -
判断plugin.install是不是函数,如果是,就利用apply方法来进行调用,this指向plugin
-
如果不是函数,就直接调用plugin