Vue如何?組件的源碼解析,vue組件源碼

來源:互聯網
上載者:User

Vue如何?組件的源碼解析,vue組件源碼

官網上關於組件繼承分為兩大類,全域群組件和局部組件。無論哪種方式,最核心的是建立組件,然後根據情境不同註冊組件。

有一點要牢記,“Vue.js 組件其實都是被擴充的 Vue 執行個體”!

1. 全域群組件

// 方式一var MyComponent = Vue.extend({  name: 'my-component',  template: '<div>A custom component!</div>'});Vue.component('my-component', MyComponent);// 方式二Vue.component('my-component', {  name: 'my-component',  template: '<div>A custom component!</div>'});// 使用組件<div id="example">  <my-component></my-component></div>

主要涉及到兩個靜態方法:

  1. Vue.extend:通過擴充Vue執行個體的方法建立組件
  2. Vue.component:註冊組件

先來看看Vue.extend源碼,解釋參考中文注釋:

Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var isFirstExtend = Super.cid === 0; if (isFirstExtend && extendOptions._Ctor) {  return extendOptions._Ctor; } var name = extendOptions.name || Super.options.name; // 如果有name屬性,即組件名稱,檢測name拼字是否合法 if ('development' !== 'production') {  if (!/^[a-zA-Z][\w-]*$/.test(name)) {   warn('Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characaters and the hyphen.');   name = null;  } } // 建立一個VueComponent 建構函式,函數名為‘VueComponent'或者name var Sub = createClass(name || 'VueComponent'); // 建構函式原型繼承Vue.prototype Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; // 合并Vue.options和extendOptions,作為新建構函式的靜態屬性options   Sub.options = mergeOptions(Super.options, extendOptions); //'super'靜態屬性指向Vue函數 Sub['super'] = Super; // start-----------------拷貝Vue靜態方法   // allow further extension Sub.extend = Super.extend; // create asset registers, so extended classes // can have their private assets too. config._assetTypes.forEach(function (type) {  Sub[type] = Super[type]; }); // end-----------------拷貝Vue靜態方法   // enable recursive self-lookup if (name) {  Sub.options.components[name] = Sub; } // cache constructor:緩衝該建構函式 if (isFirstExtend) {  extendOptions._Ctor = Sub; } return Sub;};

可以看到,Vue.extend的關鍵點在於:建立一個建構函式function VueComponent(options) { this._init(options) },通過原型鏈繼承Vue原型上的屬性和方法,再講Vue的靜態函數賦值給該建構函式。

再看看Vue.component源碼,解釋參考中文注釋:

// _assetTypes: ['component', 'directive', 'elementDirective', 'filter', 'transition', 'partial']config._assetTypes.forEach(function (type) { // 靜態方法Vue.component Vue[type] = function (id, definition) {  if (!definition) {   return this.options[type + 's'][id];  } else {   /* istanbul ignore if */   if ('development' !== 'production') {    if (type === 'component' && (commonTagRE.test(id) || reservedTagRE.test(id))) {     warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + id);    }   }   // 如果第二個參數是簡單對象,則需要通過Vue.extend建立組件建構函式   if (type === 'component' && isPlainObject(definition)) {    if (!definition.name) {     definition.name = id;    }    definition = Vue.extend(definition);   }   // 將組件函數加入Vue靜態屬性options.components中,也就是,全域注入該組件   this.options[type + 's'][id] = definition;   return definition;  } };});

方法Vue.component的關鍵點是,將組件函數注入到Vue靜態屬性中,這樣可以根據組件名稱找到對應的建構函式,從而建立組件執行個體。

2. 局部組件

var MyComponent = Vue.extend({  template: '<div>A custom component!</div>'});new Vue({  el: '#example',  components: {    'my-component': MyComponent,    'other-component': {      template: '<div>A custom component!</div>'    }  }});

註冊局部組件的特點就是在建立Vue執行個體的時候,定義components屬性,該屬性是一個簡單對象,key值為組件名稱,value可以是具體的組件函數,或者建立組件必須的options對象。

來看看Vue如何解析components屬性,解釋參考中文注釋:

Vue.prototype._init = function (options) {  options = options || {};  ....  // merge options.  options = this.$options = mergeOptions(this.constructor.options, options, this);  ...};function mergeOptions(parent, child, vm) {  //解析components屬性  guardComponents(child);  guardProps(child);  ...}function guardComponents(options) {  if (options.components) {    // 將對象轉為數組    var components = options.components = guardArrayAssets(options.components);    //ids數組包含組件名    var ids = Object.keys(components);    var def;    if ('development' !== 'production') {      var map = options._componentNameMap = {};    }    // 遍曆組件數組    for (var i = 0, l = ids.length; i < l; i++) {      var key = ids[i];      if (commonTagRE.test(key) || reservedTagRE.test(key)) {        'development' !== 'production' && warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + key);        continue;      }      // record a all lowercase <-> kebab-case mapping for      // possible custom element case error warning      if ('development' !== 'production') {        map[key.replace(/-/g, '').toLowerCase()] = hyphenate(key);      }      def = components[key];      // 如果是組件定義是簡單對象-對象字面量,那麼需要根據該對象建立組件函數      if (isPlainObject(def)) {        components[key] = Vue.extend(def);      }    }  }}

在建立Vue執行個體過程中,經過guardComponents()函數處理之後,能夠保證該Vue執行個體中的components屬性,都是由{組件名:組件函數}構成的,這樣在後續使用時,可以直接利用執行個體內部的組件構建函數建立組件執行個體。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.