天天看點

Vue之深入了解extend與手動挂載$mount

上一章節我們說到,建立一個vue執行個體的時候,都會有一個選項el,來指定執行個體的根節點,如果不寫el選項,那元件就處于未挂載狀态。​

​Vue.extend​

​​ 的作用,就是基于 Vue 構造器,建立一個“子類”,它的參數跟 ​

​new Vue​

​​ 的基本一樣,但 ​

​data​

​​ 要跟元件一樣,是個函數,再配合 ​

​$mount​

​ ,就可以讓元件渲染,并且挂載到任意指定的節點上,比如 body。
import Vue from 'vue';

const AlertComponent = Vue.extend({
  template: '<div>{{ message }}</div>',
  data () {
    return {
      message: 'Hello, Aresn'
    };
  },
});      

這一步,我們建立了一個構造器,這個過程就可以解決異步擷取 template 模闆的問題,下面要手動渲染元件,并把它挂載到 body 下:

const component = new AlertComponent().$mount();      

這一步,我們調用了 ​

​$mount​

​​ 方法對元件進行了手動渲染,但它僅僅是被渲染好了,并沒有挂載到節點上,也就顯示不了元件。此時的 ​

​component​

​​ 已經是一個标準的 Vue 元件執行個體,是以它的 ​

​$el​

​ 屬性也可以被通路:

document.body.appendChild(component.$el);      

當然,除了 body,你還可以挂載到其它節點上。

​$mount​

​ 也有一些快捷的挂載方式,以下兩種都是可以的:

// 在 $mount 裡寫參數來指定挂載的節點
new AlertComponent().$mount('#app');
// 不用 $mount,直接在建立執行個體時指定 el 選項
new AlertComponent({ el: '#app' });      

實作同樣的效果,除了用 extend 外,也可以直接建立 Vue 執行個體,并且用一個 Render 函數來渲染一個 .vue 檔案:

import Vue from 'vue';
import Notification from './notification.vue';

const props = {};  // 這裡可以傳入一些元件的 props 選項

const Instance = new Vue({
  render (h) {
    return h(Notification, {
      props: props
    });
  }
});

const component = Instance.$mount();
document.body.appendChild(component.$el);      
const notification = Instance.$children[0];      

繼續閱讀