12.vue.use是干什么的(重点)

36 阅读2分钟

概念

插件的作用:插件通常用来为Vue添加全局功能,插件的功能没有严格的限制,一般有以下几种:
  1. 添加全局方法property,如:vue-custom-element
  2. 添加全局资源:指令、过滤器、过度等,如:vue-touch
  3. 通过全局混入来添加一些组件选项,如: vue-router
  4. 添加Vue实例方法,通过把它们添加到Vue.prototype上实现
  5. 一个库,提供自己的API,同时提供上边的一种或几种功能,如: vue-router
通过全局方法 Vue.use()使用插件,它需要你在调用new Vue()启用应用之前完成。
// 调用 myPlugin.install(Vue)
Vue.use(myPlugin)

new Vue({
  // ...组件选项
})
所以,Vue.use的参数必须是一个Object对象或者function函数,如果是对象的话,必须要提供install方法,之后会将Vue作为参数传入
import { toArray } from '../util/index'
// Vue.use 源码
export function initUse (Vue: GlobalAPI) {
    // 首先先判断插件plugin是否是对象或者函数:
    Vue.use = function (plugin: Function | Object) {
        const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
        // 判断vue是否已经注册过这个插件,如果已经注册过,跳出方法
        if (installedPlugins.indexOf(plugin) > -1) {
            return this
        }
        
        // 取vue.use参数,toArray() 方法代码在下一个代码块
        const args = toArray(arguments, 1)
        args.unshift(this)
        // 判断插件是否有install方法,如果有就执行install()方法。没有就直接把plugin当Install执行。
        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: any, start?: number): Array<any> {
    start = start || 0
    let i = list.length - start
    const ret: Array<any> = new Array(i)
    while (i--) {
        ret[i] = list[i + start]
    }
    return ret
}
总结
  1. 首先判断插件 plugin 是否是对象或者函数 代码:
`plugin: Function | Object`
  1. 判断Vue是否已注册过这个插件,如果注册过就跳出方法,代码:
 const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
        // 判断vue是否已经注册过这个插件,如果已经注册过,跳出方法
        if (installedPlugins.indexOf(plugin) > -1) {
            return this
        }
  1. 处理Vue.use的入参,将第一个参数之后的参数归集,并在首部塞入this上下文,代码:
const args = toArray(arguments, 1)
args.unshift(this)
  1. 断插件是否有install方法,如果有就执行install()方法。没有就直接把plugin当Install执行。代码:
 if (typeof plugin.install === 'function') {
     plugin.install.apply(plugin, args)
 } else if (typeof plugin === 'function') {
     plugin.apply(null, args)
 }
  1. 缓存插件:
installedPlugins.push(plugin)