在使用 vue-router 、 iview 、vuex 的时候,我们都会用到 Vue.use() 。那么,到底 Vue.use() 是什么,又是为什么可以使用 Vue.use() 呢?
我们可以简单理解,一个有 install 方法的组件,就可以通过 Vue.use() 来引用。这样写的好处就是插件需要一开始调用的方法都封装在 install 里面,更加精简和可扩展性更高。

Vue.use() 必须传入一个参数,该参数类型必须是 Object 或者 Function 。如果是 Object ,那么这个 Object 必须定义一个 install 方法,如果是 Function ,那么这个函数就被当作是 install 方法。在 Vue.use() 执行时 install 会默认执行。

下面举一个新建一个插件可以被 Vue.use 调用的插件的例子:

  1. MyPlugin.install = function(Vue, options) {
  2. // 全局注册组件(指令等功能资源类似)
  3. Vue.component('component-name', {
  4. // 组件内容
  5. })
  6. // 添加实例方法
  7. Vue.prototype.$Notice = function() {
  8. // 逻辑
  9. }
  10. // 添加全局方法或属性
  11. Vue.globalMethod = function() {
  12. // 逻辑
  13. }
  14. // 添加全局混合
  15. Vue.mixin({
  16. mounted: function() {
  17. // 逻辑
  18. }
  19. })

通过 Vue.use() 来使用插件:

  1. Vue.use(MyPlugin)
  2. // 或
  3. Vue.use(MyPlugin, {
  4. // 参数
  5. })

Vue.use() 源码解析

源码位置:vue/src/core/global-api/use.js

  1. /* @flow */
  2. import { toArray } from '../util/index'
  3. export function initUse (Vue: GlobalAPI) {
  4. Vue.use = function (plugin: Function | Object) {
  5. // 存储已经装载过的插件
  6. const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
  7. // 同一个插件只能注册一次
  8. if (installedPlugins.indexOf(plugin) > -1) {
  9. return this
  10. }
  11. // additional parameters
  12. const args = toArray(arguments, 1)
  13. // 将 Vue 对象拼接到数组头部
  14. args.unshift(this)
  15. if (typeof plugin.install === 'function') {
  16. // 如果传入的是对象,且提供了 install 方法,则调用 install 方法
  17. plugin.install.apply(plugin, args)
  18. } else if (typeof plugin === 'function') {
  19. // 如果传入的是函数,则直接调用
  20. plugin.apply(null, args)
  21. }
  22. installedPlugins.push(plugin)
  23. return this
  24. }
  25. }
  1. // toArray 方法源码
  2. export function toArray (list: any, start?: number): Array<any> {
  3. start = start || 0
  4. let i = list.length - start
  5. const ret: Array<any> = new Array(i)
  6. while (i--) {
  7. ret[i] = list[i + start]
  8. }
  9. return ret
  10. }