Vue 基礎知識之 Vue.extend

Vue.extend 屬於 Vue 的全局 API,在實際業務開發中咱們不多使用,由於相比經常使用的 Vue.component 寫法使用 extend 步驟要更加繁瑣一些。可是在一些獨立組件開發場景中,Vue.extend + $mount 這對組合是咱們須要去關注的。html

官方文檔

學習開始以前咱們先來看一下官方文檔是怎麼描述的。vue

Vue.extend( options )

  • 參數api

    • {Object} options
  • 用法app

    使用基礎 Vue 構造器,建立一個「子類」。參數是一個包含組件選項的對象。ide

    data 選項是特例,須要注意 - 在 Vue.extend() 中它必須是函數函數

    <div id="mount-point"></div>
    // 建立構造器
    var Profile = Vue.extend({
      template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
      data: function () {
        return {
          firstName: 'Walter',
          lastName: 'White',
          alias: 'Heisenberg'
        }
      }
    })
    // 建立 Profile 實例,並掛載到一個元素上。
    new Profile().$mount('#mount-point')

    結果以下:學習

    <p>Walter White aka Heisenberg</p>
  • 參考組件ui

能夠看到,extend 建立的是 Vue 構造器,而不是咱們平時常寫的組件實例,因此不能夠經過 new Vue({ components: testExtend }) 來直接使用,須要經過 new Profile().$mount('#mount-point') 來掛載到指定的元素上。code

爲何使用 extend

在 vue 項目中,咱們有了初始化的根實例後,全部頁面基本上都是經過 router 來管理,組件也是經過 import 來進行局部註冊,因此組件的建立咱們不須要去關注,相比 extend 要更省心一點點。可是這樣作會有幾個缺點:component

  1. 組件模板都是事先定義好的,若是我要從接口動態渲染組件怎麼辦?
  2. 全部內容都是在 #app 下渲染,註冊組件都是在當前位置渲染。若是我要實現一個相似於 window.alert() 提示組件要求像調用 JS 函數同樣調用它,該怎麼辦?

這時候,Vue.extend + vm.$mount 組合就派上用場了。

簡單示例

咱們照着官方文檔來建立一個示例:

import Vue from 'vue'

const testComponent = Vue.extend({
  template: '<div>{{ text }}</div>',
  data: function () {
    return {
      text: 'extend test'
    }
  }
})

而後咱們將它手動渲染:

const extendComponent = new testComponent().$mount()

這時候,咱們就將組件渲染掛載到 body 節點上了。

咱們能夠經過 $el 屬性來訪問 extendComponent 組件實例:

document.body.appendChild(extendComponent.$el)

若是想深刻掌握 extend 知識,不妨作一個 alert 組件來實現相似於原生的全局調用。

加油!

相關文章
相關標籤/搜索