iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 13
0
Modern Web

技術在走,Vue.js 要有系列 第 13

|D13| 從原始碼看 Vue 元件化 (6) - 元件註冊

全域註冊

Vue.component('my-component', {
  // 設定屬性、方法等
})

在初始化 Vue 的全域函數時,也定義了 Vue.component

// src/core/global-api/assets.js

import { ASSET_TYPES } from 'shared/constants'
import { isPlainObject, validateComponentName } from '../util/index'
export function initAssetRegisters (Vue: GlobalAPI) {
    /******************************************
       遍歷 ASSET_TYPES 把 type 掛載到 Vue 上
    ******************************************/
  ASSET_TYPES.forEach(type => {
    Vue[type] = function (
      id: string,
      definition: Function | Object
    ): Function | Object | void {
      if (!definition) {
        return this.options[type + 's'][id]
      } else {
        if (process.env.NODE_ENV !== 'production' && type === 'component') {
          validateComponentName(id)
        }
        if (type === 'component' && isPlainObject(definition)) {
          definition.name = definition.name || id
           /**************************************************
               如果 type 是 component 且 definition 是一個物件,
               則執行 this.opitons._base.extend
            **************************************************/
          definition = this.options._base.extend(definition)
        }
        if (type === 'directive' && typeof definition === 'function') {
          definition = { bind: definition, update: definition }
        }
        /**************************************************
           掛載到 Vue.options.components 上
        **************************************************/
        this.options[type + 's'][id] = definition
        return definition
      }
    }
  })
}

// src/shared/constants.js
/******************************************
  ASSET_TYPES 定義如下,Vue 初始化了 3 個全域函数
******************************************/
export const ASSET_TYPES = [
  'component',
  'directive',
  'filter'
]

局部註冊

import HelloWorld from './components/HelloWorld'

export default {
  components: {
    HelloWorld
  }
}

局部註冊是在元件的 Vue 實例化時有一段合併 option 的程式碼,把 components 合併到 vm.$options.components 上。


上一篇
|D12| 從原始碼看 Vue 元件化 (5) - updateChildren,新增和刪除子節點
下一篇
|D14| 從原始碼看 Vue 元件化 (7) - 異步元件
系列文
技術在走,Vue.js 要有30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言