Vue中注册插件(Vue.use)

84 阅读1分钟

官网地址 学习地址

Vue提供了Vue.use来注册插件。

  1. Vue.use参数为函数时,函数的参数是Vue对象
  2. Vue.use参数为对象时,它提供的install方法中参数是Vue对象
/* @flow */

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

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    // 判断是否已经安装了,如果已经安装过了,就直接return
    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.component()和Vue.use()的对比

- Vue.component

Vue.component()用于全局注册一个组件。全局注册的组件可以在任何Vue实例的模板中使用。 特点:

  1. 全局使用:一旦注册,全局组件可以在任意Vue实例中使用。
  2. 全局命名空间:组件名称注册到全局命名空间中,所以必须保证名称唯一,避免冲突。
  3. 简单使用:不需要额外配置可以在任何模板中使用。

当你需要定义一个可以在多个地方使用的全局组件时使用。

- Vue.use

Vue.use()用于安装插件。插件通常为Vue添加全局功能。 特点:

  1. 扩展功能:插件通常用于向Vue添加全局功能或行为。
  2. 可选配置:插件可以接收配置选项,以便在安装时进行自定义。
  3. 全局安装:一旦通过Vue.use()安装,插件功能在所有Vue实例中可用。

当你需要向Vue添加全局功能或行为(例如全局方法、指令、混入等)时使用。