Vue組件實例建立的方法

Vue組件實例的建立能夠經過Vue.extend()或render函數來實現,下面簡單介紹下:bash

1. Vue.extend()

大體步驟以下:markdown

  • 經過配置項獲取組件的構造函數
  • 實例化構造函數,生成虛擬dom
  • 組件掛載,虛擬dom轉成真實dom,並追加到dom節點中

代碼以下:app

// 參數Component爲組件配置項,返回組件實例
function create(Component, props){
    // 經過Component配置項獲取組件的構造函數
    // 使用 Vue.extend(Component) 實現
    const Constructor = Vue.extend(Component);
    // 建立組件實例,生成的是虛擬dom
    // 爲避免props屬性重名,使用propsData屬性
    const comp = new Constructor({
        propsData: props
    })
    // 組件掛載到id爲app的節點中,虛擬dom掛載後才能生成真實dom
    comp.$mount('#app');
    
    return comp;
}
複製代碼

2. render()

大體實現步驟以下:dom

  • 經過Component配置項獲取組件的構造函數
  • 實例化組件構造函數
  • 組件掛載,虛擬dom轉成真實dom,追加到頁面節點中

代碼以下:函數

function create(Component, props){
    // 經過Component配置項獲取組件的構造函數
    // 經過render函數實現
    // vm就是組件實例
    const vm = new Vue({
        // h是createElement,返回VNode, VNode是虛擬dom
        // 須要掛載才能變成真實Dom
        render: h => h(Component, {props})
    })
    // $mount(elem)指定宿主元素,則會建立真實dom,並追加到指定節點
    vm.$mount('#app');
    
    const comp = vm.$children[0]
    return comp;
}
複製代碼
相關文章
相關標籤/搜索