上一篇:Vue原理解析(十):搞懂事件API原理及在組件庫中的妙用html
在學習老黃的Vue2.0開發企業級移動端音樂Web App課程時,裏面有一個精美的確認彈窗組件,以下: vue
ref
引用,須要調用事件來控制狀態。其實這個組件相對來講是比較獨立的,咱們在使用組件庫的時候,相信都有調用過命令式彈窗組件的經歷,今天咱們就來搞懂這種命令式組件的實現原理,以及將這個精美的彈窗組件改成命令式的,也就是這樣調用:
this.$Confirm({...})
.then(confirm => {
...
})
.catch(cancel => {
...
})
複製代碼
這兩個都是vue
提供的API
,不過在平時的業務開發中使用並很少。在vue
的內部也有使用過這一對API
。遇到嵌套組件時,首先將子組件轉爲組件形式的VNode
時,會將引入的組件對象使用extend
轉爲子組件的構造函數,做爲VNode
的一個屬性Ctor
;而後在將VNode
轉爲真實的Dom
的時候實例化這個構造函數;最後實例化完成後手動調用$mount
進行掛載,將真實Dom
插入到父節點內完成渲染。面試
因此這個彈窗組件能夠這樣實現,咱們本身對組件對象使用
extend
轉爲構造函數,而後手動調用$mount
轉爲真實Dom
,由咱們來指定一個父節點讓它插入到指定的位置。bash
在動手前,咱們再多花點時間深刻理解下流程細節:app
接受的是一個組件對象,再執行
extend
時將繼承基類構造器上的一些屬性、原型方法、靜態方法等,最後返回Sub
這麼一個構造好的子組件構造函數。擁有和vue
基類同樣的能力,並在實例化時會執行繼承來的_init
方法完成子組件的初始化。ide
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 // 返回子組件的構造函數
}
複製代碼
執行
_init
組件初始化的一系列操做,初始化事件、生命週期、狀態等等。將data
或props
內定義的變量掛載到當前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) // 執行掛載
}
}
複製代碼
在獲得初始化後的對象後,開始組件的掛載。首先將當前
render
函數轉爲VNode
,而後將VNode
轉爲真實Dom
插入到頁面完成渲染。再完成掛載以後,會在當前組件實例this
下掛載$el
屬性,它就是完成掛載後對應的真實Dom
,咱們就須要使用這個屬性。post
由於是
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(); // 執行組件銷燬
}
}
};
複製代碼
組件對象已經有了,接下來就是將它轉爲命令式可調用的:flex
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
對象。
在
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>
複製代碼
試着實現一個全局的提醒組件吧,原理差很少的~
最後按照慣例咱們仍是以一道vue
可能會被問到的面試題做爲本章的結束~
面試官微笑而又不失禮貌的問道:
懟回去:
extend
將組件轉爲構造函數,在實例化這個這個構造函數後,就會獲得$el
屬性,也就是組件的真實Dom
,這個時候咱們就能夠操做獲得的真實的Dom
去任意掛載,使用命令式也能夠調用。下一篇: 埋頭書寫中...
順手點個贊或關注唄,找起來也方便~