首頁  >  文章  >  web前端  >  分析一下Vue.use的源碼

分析一下Vue.use的源碼

青灯夜游
青灯夜游轉載
2020-10-29 17:55:262392瀏覽

分析一下Vue.use的源碼

有過vue開發經驗的,對於vue.use並不陌生。當使用vue-resource或vue-router等全域元件時,必須透過Vue.use方法引入,才會起作用。那麼vue.use在元件引進之前到底做了那些事情呢?

先上vue.use原始碼

Vue.use = function (plugin) {
    /* istanbul ignore if */
    if (plugin.installed) {
      return
    }
    // additional parameters
    var 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);
    }
    plugin.installed = true;
    return this
  };

假設我們透過Vue.use引入一個插件plugin(該插件可以暫時理解為一個變數或參數),即Vue.use(plugin);

先判斷傳入的參數plugin的屬性installed是否存在,如果存在且邏輯值為真,那麼直接返回,後邊的程式碼就不會在執行,這個判斷的作用是什麼呢?後邊會講到。

我們先假設plugin的屬性installed不存在或為假,那麼繼續往下執行

var args = toArray(arguments, 1)

執行了一個toArray方法,toArray接收了兩個參數,arguments為Vue .use方法傳入的參數集合,例如Vue.use(a,b,c),那麼arguments類似於[a,b,c](說明:arguments只是類別數組,並不是真正的數組)

這裡因為我們只引入一個參數plugin,所以arguments類似[plugin]。

toArray的作用是什麼呢?看源碼。

function toArray (list, start) {
  start = start || 0;
  var i = list.length - start;
  var ret = new Array(i);
  while (i--) {
    ret[i] = list[i + start];
  }
  return ret
}

當執行toArray(arguments,1),會產生一個新數組ret,長度= arguments.length-1,然後進行while循環,依次倒序把arguments的元素賦值為ret,因為ret比arguments長度少1.

所以最後等同於arguments把除了第一個元素外的其餘元素賦值給ret。 toArray主要作用就是把類別數組轉換成真正的數組,這樣才能呼叫數組的方法。

因為這裡我只引入一個plugin參數,即arguments=[plugin],所以toArray回傳為空數組[]。

接著往下執行,args.unshift(this),等同於[].unshift(Vue),即args = [Vue];

然後執行

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

此處判斷plugin的install是否為函數,如果為函數,立即執行pluign.install方法,install方法傳入的參數為args內數組元素,即install接受的第一個參數為Vue.

#如果plugin的install不是函數,那麼判斷plugin本身是否為函數,如果為函數,那麼執行plugin函數,且參數為args內數組元素。

最後設定plugin.installed為true。設定plugin.installed為true的作用是避免同一個插件多次執行安裝,例如Vue.use(plugin)執行一次之後,installed為true,再次執行的話走到第一步判斷就返回了。

綜上所述,Vue.use的作用其實就是執行一個plugin函數或執行pluign的install方法進行插件註冊,並且向plugin或其install方法傳入Vue物件作為第一個參數,use的其他參數作為plugin或install的其他參數。

舉個簡單的例子

import Vue from 'vue'
function test(a){
   console.log(a);//Vue
}
function test1(a,b){
  console.log(a,b);//Vue hello
}
let oTest = {
   install:function(a,b){
      console.log(a,b);//Vue hello1
   }
}
Vue.use(test);
Vue.use(test1,'hello');
Vue.use(oTest,'hello1')
console.log(oTest);
//{
  install:function(){...},
  installed:true
}

相關推薦:

#2020年前端vue面試題大總結(附答案)

vue教學推薦:2020最新的5個vue.js影片教學精選

更多程式相關知識,請造訪:程式設計入門! !

以上是分析一下Vue.use的源碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除