vue2源码笔记之Vue.use

用法

Vue.use( plugin )
复制代码

安装插件,如果插件是一个对象,则必须要提供一个install方法。
如果插件是个函数,它会被作为install方法。
调用install方法时, 会将Vue作为参数传入;
install方法被同一个插件调用多次时, 插件也只会被安装一次

// s-pdf/index.js
import SPdf from './src/s-pdf';

SPdf.install = function(Vue) {
  Vue.component(SPdf.name, SPdf);
};

export default SPdf;

// main.js
import SPdf from 's-pdf'
Vue.use(SPdf)
复制代码

源码实现

export function initUse (Vue) {
    Vue.use = function (plugin){
        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
    }
}


// 其中toArray方法
export function toArray (list, start) {
  start = start || 0
  let i = list.length - start
  const ret = new Array(i)
  while (i--) {
    ret[i] = list[i + start]
  }
  return ret
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享