vue

Vue.use解析

2020-03-15  本文已影响0人  solfKwolf

Vue.use

源码解析

import { initUse } from './use'
// 注入use方法
initUse(Vue)
import { toArray } from '../util/index'

export function initUse (Vue: GlobalAPI) {
   // 绑定use方法
  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') {
      // 调用install方法,并绑定this
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }
    // 添加插件到列表
    installedPlugins.push(plugin)
     //   返回Vue实例
    return this
  }
}

上面的代码可以看出,Vue.Use方法会调用插件对象的install方法(或者插件函数)。并将this传递给install函数作为第一个参数。

上一篇 下一篇

猜你喜欢

热点阅读