解读Vue.use()源码

Vue.use()

vue.use()的做用:


官方文档的解释:vue

安装 Vue.js 插件。若是插件是一个对象,必须提供 install 方法。若是插件是一个函数,它会被做为 install 方法。install 方法调用时,会将 Vue 做为参数传入。

vue.use()使用情景:


能够在项目中使用vue.use()全局注入一个插件,从而不须要在每一个组件文件中import插件。例如:
不使用vue.use()注入插件:vue-router

const utils = require('./utils')
// 或者
import utils from './utils'

使用vue.use()注入插件,最典型的案例:数组

import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

使用了vue.use()注册插件以后就能够在全部的vue文件中使用路由:
this.$routeapp

vue.use()源码


下面切入本文的主题。咱们知道了vue.use()怎么用还不够,还要知道它的内部是怎么实现的。下面展现源码:ide

import { toArray } from '../util/index'

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    if (installedPlugins.indexOf(plugin) > -1) {
      return this
    }

    // additional parameters
    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
  }
}

vue.use()源码中采用了flow的语法。flow语法,官方解释是:函数

Flow is a static type checker for your JavaScript code. It does a lot of work to make you more productive. Making you code faster, smarter, more confidently, and to a bigger scale.

简单的意思就是flow是JavaScript代码的静态类型检查工具。官网连接
使用flow的好处就是:在编译期对js代码变量作类型检查,缩短调试时间, 减小因类型错误引发的bug。咱们都知道js是解释执行语言,运行的时候才检查变量的类型,flow能够在编译阶段就对js进行类型检查。工具

下面将对vue.use()源码进行解读:ui

一、首先先判断插件plugin是不是对象或者函数:
Vue.use = function (plugin: Function | Object)this

二、判断vue是否已经注册过这个插件
installedPlugins.indexOf(plugin) > -1
若是已经注册过,跳出方法插件

三、取vue.use参数。
const args = toArray(arguments, 1)

四、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
  }

let i = list.length - start意思是vue.use()方法传入的参数,除第一个参数外(第一个参数是插件plugin),其余参数都存储到一个数组中,而且将vue对象插入到参数数组的第一位。最后参数数组就是[vue,arg1,arg2,...]

五、判断插件是否有install方法,若是有就执行install()方法。没有就直接把plugin当Install执行。

if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }

plugin.install.apply(plugin, args)将install方法绑定在plugin环境中执行,而且传入args参数数组进install方法。此时install方法内的this指向plugin对象。
plugin.apply(null, args) plugin内的this指向null.

最后告知vue该插件已经注册过installedPlugins.push(plugin)保证每一个插件只会注册一次。

总结


使用vue.use()注册插件,插件能够是一个函数,能够是一个带有install属性的对象。无论是函数仍是install方法,第一个参数老是vue对象。
我的仍是喜欢使用将插件的功能方法写在install方法里。由于install内的this指向的是plugin对象自身,扩展性更好。

相关文章
相关标签/搜索