vue中使用插件的形式

在使用elementUI时 使用按需引入 发现官方推荐的方式是分开use
例如
Vue.use(Table)
Vue.use(TableColumn)
但是我发现这样也可以
vue.use(Table).use(TableColumn)
有点疑惑 不明白两者的区别 可以讲解一下吗

阅读 2.7k
3 个回答

use方法的源码如下:

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
    }
    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,在Vue.use(xxx)中,也就相当于返回了Vue. 所以可以继续调用use方法

应该是Vue.use(Table)也返回了Vue对象,这时可以链式调用。
如果你使用过jquery的话,到处是这样的写法。
没有区别。有的人喜欢这样写,能少点儿代码。缺点是出错时不一定好调试。

Vue.use(Table)
Vue.use(TableColumn)

vue.use(Table).use(TableColumn)
是等效的

你可以这么理解use方法:

use (){
    // ...
    return this
}

所以可以链式调用

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题