Vue原理解析(十一) 之 extend 和$mount 原理及示例

上一篇: Vue 原理解析(十):之 事件API 原理及組件庫的使用

之前在網上看到一個精美的確認彈框組件。 不過使用起來並不是很方便, 如果每個使用的地方需要引入該組件,需要註冊, 需要給組件加ref 引用, 需要調用事件來控制狀態。 其實這個組件相對來說比較獨立的, 我們在使用組件庫的時候, 相信都有調用過命令式彈框組件的經歷, 今天我們來搞懂命令式組件的實現原理, 以及將這個精美的彈窗組件改爲命令式的, 也就是這樣調用:

this.$Confirm({...})
  .then(confirm => {
    ...
  })
  .catch(cancel => {
    ...
  })

原理解析值 extend 和 $mount

這兩個都是vue 提供的 API, 不過在平時的業務開發中使用並不多。 在vue的內部也有使用過這一對API。 遇到嵌套組件時, 首先將子組件轉爲組件形式的VNode 時, 會將引入的組件對象使用extend 轉爲子組件的構造函數, 作爲Vnode 的一個屬性Ctor; 然後在將VNode 轉爲真是的Dom的時候實例化這個構造函數; 最後實例化完成後手動調用==$mount== 進行掛載, 將真實Dom插入到父節點內完成渲染。

所以這個彈框組件可以這樣實現, 我們自己對組件對象使用extend 轉爲構造函數, 然後手動調用 $mount 轉爲真實Dom, 由我們來指定一個父節點讓它插入到指定的位置。

在動手前, 再花點時間理解下流程細節:

extend

接受的是一個組件對象, 再執行extend 時將繼承基類構造器上的一些屬性, 原型方法, 靜態方法等, 最後返回Sub 這麼一個構造好的子組件構造函數。 擁有和 vue基類一樣的能力, 並在實例化時會執行繼承來的==_init==方法完成子組件的初始化。

Vue.extend = function (extendOptions = {}) {
  const Super = this  // Vue基類構造函數
  const name = extendOptions.name || Super.options.name
  
  const Sub = function (options) {  // 定義構造函數
    this._init(options)  // _init繼承而來
  }
  
  Sub.prototype = Object.create(Super.prototype)  // 繼承基類Vue初始化定義的原型方法
  Sub.prototype.constructor = Sub  // 構造函數指向子類
  Sub.options = mergeOptions( // 子類合併options
    Super.options,  // components, directives, filters, _base
    extendOptions  // 傳入的組件對象
  )
  Sub['super'] = Super // Vue基類

  // 將基類的靜態方法賦值給子類
  Sub.extend = Super.extend
  Sub.mixin = Super.mixin
  Sub.use = Super.use

  ASSET_TYPES.forEach(function (type) { // ['component', 'directive', 'filter']
    Sub[type] = Super[type]
  })
  
  if (name) {  讓組件可以遞歸調用自己,所以一定要定義name屬性
    Sub.options.components[name] = Sub  // 將子類掛載到自己的components屬性下
  }

  Sub.superOptions = Super.options
  Sub.extendOptions = extendOptions

  return Sub  // 返回子組件的構造函數
}

實例化Sub

執行==_init== 組件初始化的一系列操作, 初始化事件, 生命週期, 狀態等等。 將 dataprops 內定義的變量掛載到當前this實例下, 最後返回一個實例化後的對象。

Vue.prototype._init = function(options) {  // 初始化
  ...
  initLifecycle(vm)
  initEvents(vm)
  initRender(vm)
  callHook(vm, 'beforeCreate')
  initInjections(vm)
  initState(vm)
  initProvide(vm)
  callHook(vm, 'created')  // 初始化階段完成
  ...
  
  if (vm.$options.el) {  // 開始掛載階段
    vm.$mount(vm.$options.el)  // 執行掛載
  }
}

$mount

在得到初始化後的對象, 開始組件的掛載。 首先當前render 函數轉爲VNode, 然後將VNode 轉爲真實Dom 插入到頁面完成渲染。 在完成掛載之後, 會在當前組件實例this 下掛載 $el 屬性, 它就是完成掛載後對應的真實Dom, 我們就需要使用在這屬性。

組件改造

1. 寫出組件(完整代碼在隨後)

因爲是Promise 的方式調用, 所以顯示後返回Promise 對象, 這裏只放出主要的 Javascript 部分:

export default {
  data() {
    return {
      showFlag: false,
      title: "確認清空所有歷史紀錄嗎?",  // 可以使用props
      ConfirmBtnText: "確定",  // 爲什麼不用props接受參數
      cancelBtnText: "取消"  // 之後會明白
    };
  },
  methods: {
    show(cb) {  // 加入一個在執行Promise前的回調
      this.showFlag = true;
      typeof cb === "function" && cb.call(this, this);
      return new Promise((resolve, reject) => { // 返回Promise
        this.reject = reject;  // 給取消按鈕使用
        this.resolve = resolve;  // 給確認按鈕使用
      });
    },
    cancel() {
      this.reject("cancel");  // 拋個字符串
      this.hide();
    },
    confirm() {
      this.resolve("confirm");
      this.hide();
    },
    hide() {
      this.showFlag = false;
      document.body.removeChild(this.$el);  // 結束移除Dom
      this.$destroy();  // 執行組件銷燬
    }
  }
};

2. 轉換調用方式

組件對象已經有了, 接下來就是將它轉爲命令式可調用的:

confirm/index.js

import Vue from 'vue';
import Confirm from './confirm';  // 引入組件

let newInstance;
const ConfirmInstance = Vue.extend(Confirm);  // 創建構造函數

const initInstance = () => { // 執行方法後完成掛載
  newInstance = new ConfirmInstance();  // 實例化
  document.body.appendChild(newInstance.$mount().$el);
  // 實例化後手動掛載,得到$el真實Dom,將其添加到body最後
}

export default options => { 導出一個方法,接受配置參數
  if (!newInstance) {
    initInstance(); // 掛載
  }
  Object.assign(newInstance, options);
  // 實例化後newInstance就是一個對象了,所以data內的數據會
  // 掛載到this下,傳入一個對象與之合併
  
  return newInstance.show(vm => {  // 顯示彈窗
    newInstance = null;  // 將實例對象清空
  })
}

這裏其實可使用install 做成一個插件, 還沒有介紹就略過了。 首先使用extend將組件對象轉換爲組件構造函數, 執行initInstance 方法後就會將真實Dom掛載到body的最後。 爲什麼之前不使用props 而是使用data, 因爲他們初始化都會掛載到this下, 不過data代碼量少。 導出一個方法給到外部使用, 接受配置參數, 調用後返回一個Promise對象。

3. 掛載到全局

main.js 內導出的方法掛載到Vue的原型上, 讓其成爲一個全局方法:

import Confirm from './base/confirm/index';

Vue.prototype.$Confirm = Confirm;

試試這樣調用吧~
this.$Confirm({
  title: 'vue大法好!'
}).then(confirm => {
  console.log(confirm)  
}).catch(cancel => {
  console.log(cancel)
})

組件完整代碼如下:

confirm/confirm.vue

<template>
  <transition name="confirm-fade">
    <div class="confirm" v-show="showFlag">
      <div class="confirm-wrapper">
        <div class="confirm-content">
          <p class="text">{{title}}</p>
          <div class="operate" @click.stop>
            <div class="operate-btn left" @click="cancel">{{cancelBtnText}}</div>
            <div class="operate-btn" @click="confirm">{{ConfirmBtnText}}</div>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  data() {
    return {
      showFlag: false,
      title: "確認清空所有歷史紀錄嗎?", 
      ConfirmBtnText: "確定",
      cancelBtnText: "取消"
    };
  },
  methods: {
    show(cb) {
      this.showFlag = true;
      typeof cb === "function" && cb.call(this, this);
      return new Promise((resolve, reject) => {
        this.reject = reject;
        this.resolve = resolve;
      });
    },
    cancel() {
      this.reject("cancel");
      this.hide();
    },
    confirm() {
      this.resolve("confirm");
      this.hide();
    },
    hide() {
      this.showFlag = false;
      document.body.removeChild(this.$el);
      this.$destroy();
    }
  }
};
</script>

<style scoped lang="stylus">
.confirm {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 998;
  background-color: rgba(0, 0, 0, 0.3);
  &.confirm-fade-enter-active {
    animation: confirm-fadein 0.3s;
    .confirm-content {
      animation: confirm-zoom 0.3s;
    }
  }
  .confirm-wrapper {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;
    .confirm-content {
      width: 270px;
      border-radius: 13px;
      background: #333;
      .text {
        padding: 19px 15px;
        line-height: 22px;
        text-align: center;
        font-size: 18px;
        color: rgba(255, 255, 255, 0.5);
      }
      .operate {
        display: flex;
        align-items: center;
        text-align: center;
        font-size: 18px;
        .operate-btn {
          flex: 1;
          line-height: 22px;
          padding: 10px 0;
          border-top: 1px solid rgba(0, 0, 0, 0.3);
          color: rgba(255, 255, 255, 0.3);
          &.left {
            border-right: 1px solid rgba(0, 0, 0, 0.3);
          }
        }
      }
    }
  }
}
@keyframes confirm-fadein {
  0% {opacity: 0;}
  100% {opacity: 1;}
}
@keyframes confirm-zoom {
  0% {transform: scale(0);}
  50% {transform: scale(1.1);}
  100% {transform: scale(1);}
}
</style>

試着實現一個全局的提醒組件吧, 原理差不多~

最後我們還是用一個問題來結束本章內容~

  • 請說明下組件庫中命令式彈框的原理?

解答:

  • 使用extend 將組件轉爲構造函數, 在實例化這個構造函數後, 就會得到==$el== 屬性, 也就是組件的真實Dom, 這個時候我們就可以操作得到的真實dom去任意掛載, 使用命令式也可以調用。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章