04-Vue的插件機制

Vue是支持插件的,而且它的插件機制很簡單。就是用Vue.use方法,接收一個函數。接收的這個函數就是用來插件,它能做的事情無非就是在Vue或Vue.prototoye上添加一些方法啥的。讓你在Vue上或Vue實例上可以調用你插件提供的功能。

在使用use註冊插件的時候就會調用你傳遞過來的函數,這個函數接收的參數是你調用use時傳遞來的除了這個函數之外的所有參數,同時還會把Vue放到第一個參數的位置。就是const args = toArray(arguments, 1)
args.unshift(this)這兩句。

在core/global-api/use.js

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
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章