vue.use()

需要使用vue.use()安装的插件,要含有install

vue.use()可以对Vue添加全局功能

全局功能包括:

  1. 添加全局方法或者 property。如:vue-custom-element

  2. 添加全局资源:指令/过滤器/过渡等。如 vue-touch

  3. 通过全局混入来添加一些组件选项。如 vue-router

  4. 添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。

  5. 一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router

use源码:

/* @flow */

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

可以看出,use执行时走以下逻辑:

首先判断this._installedPlugins这个数组变量中是否已包含参数plugin,若包含包含则不再执行下面的逻辑(此处实现插件多次use也只安装一次的效果)

若不包含则取use方法的除第一位的其他参数(此处实现插件的传参的效果,例如:Vue.use(plugin,参数))

取得其他参数后,在参数的第一位添加this(this就是Vue类的this,绑定在this上的全局功能,也就是绑定在Vue类的全局功能,new Vue实例时,这些全局功能也就存在于vue实例上了)

  若use传的参数plugin的install是一个function时执行install并传入之前逻辑得到的参数数组

  若use传的参数plugin是function时执行plugin并传入之前逻辑得到的参数数组

installedPlugins数组添加plugin,也就是this._installedPlugins的数组添加plugin

 

于是在插件编写时添加全局变量的方法

MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或 property
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }

  // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })

  // 3. 注入组件选项
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })

  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}

 

posted @ 2020-05-12 11:33  瑞瑞大人  阅读(1582)  评论(0编辑  收藏  举报