国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Vue如何實現組件的源碼解析

2019-11-19 16:23:22
字體:
來源:轉載
供稿:網友

官網上關于組件繼承分為兩大類,全局組件和局部組件。無論哪種方式,最核心的是創建組件,然后根據場景不同注冊組件。

有一點要牢記,“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屬性,都是由{組件名:組件函數}構成的,這樣在后續使用時,可以直接利用實例內部的組件構建函數創建組件實例。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 白水县| 宁强县| 手游| 东乌珠穆沁旗| 冀州市| 理塘县| 通州市| 道真| 象州县| 平山县| 翁源县| 伊通| 元阳县| 大埔区| 永和县| 方山县| 潞城市| 临江市| 沂南县| 博罗县| 昭觉县| 普兰县| 平乡县| 洛扎县| 策勒县| 奉化市| 凉城县| 富阳市| 临桂县| 扶沟县| 峨边| 金堂县| 鹿邑县| 北川| 永丰县| 大足县| 贵港市| 黑水县| 萍乡市| 武安市| 茌平县|