Vue.use原理及源碼解讀


vue.use(plugin, arguments) 語法

  》參數:plugin(Function | Object)

  》用法:

    如果vue安裝的組件類型必須為Function或者是Object;

    如果是個對象,必須提供install方法;

    如果是一個函數,會被直接當作install函數執行;

    install函數接受參數,默認第一個參數為Vue,其后參數為注冊組件時傳入的arguments;

組件.js
    export const testObj = {
        install(Vue, arg) {
            
        }
    }
    export const testFn = founction(Vue, arg) {
        
    }
    
index.js
    import { testObj, testFn } from './組建.js'
    Vue.use(testObj, arg)
    Vue.use(testFn, arg)
    

  建議組件采用第一種寫法,根據use源碼,當采用第二種寫法時,this指針指向null

  

if (typeof plugin.install === 'function') {
    plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
    plugin.apply(null, args)
}

  官方Vue.user()源碼分析

// Vue源碼文件路徑:src/core/global-api/use.js
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 Vue對象
     return this
   }
//調用`toArray`方法
   const args = toArray(arguments, 1)
   args.unshift(this)
//將Vue對象拼接到數組頭部
   if (typeof plugin.install === 'function') {
//如果組件是對象,且提供install方法,調用install方法將參數數組傳入,改變`this`指針為該組件
     plugin.install.apply(plugin, args)
   } else if (typeof plugin === 'function') {
//如果傳入組件是函數,這直接調用,但是此時的`this`指針只想為`null` 
     plugin.apply(null, args)
   }
//在保存注冊組件的數組中添加
   installedPlugins.push(plugin)
   return this
 }
}

  toArray方法源碼

export function toArray (list: any, start?: number): Array<any> {
  start = start || 0
  let i = list.length - start
//將存放參數的數組轉為數組,並除去第一個參數(該組件)
  const ret: Array<any> = new Array(i)
//循環拿出數組
  while (i--) {
    ret[i] = list[i + start]
  }
  return ret
}

 

 

原博地址:https://www.jianshu.com/p/710fbbff15ba

相關博客:https://www.jianshu.com/p/89a05706917a

     https://segmentfault.com/a/1190000012296163


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM