幾乎每個項目都要用模態框。由於手上項目裡 alert 與 confirm 是兩套完全不同的設計,我把它們拆成了兩個組件,這裡主要討論 confirm。
<template>
<div class="modal" v-show="show" transition="fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- 頭部 -->
<div class="modal-header">
<slot name="header">
<p class="title">{{modal.title}}</p>
</slot>
<a v-touch:tap="close(0)" class="close" href="javascript:void(0)"></a>
</div>
<!-- 內容區域 -->
<div class="modal-body">
<slot name="body">
<p class="notice">{{modal.text}}</p>
</slot>
</div>
<!-- 尾部,操作按鈕 -->
<div class="modal-footer">
<slot name="button">
<a v-if="modal.showCancelButton" href="javascript:void(0)"
class="button {{modal.cancelButtonClass}}" v-touch:tap="close(1)">{{modal.cancelButtonText}}</a>
<a v-if="modal.showConfirmButton" href="javascript:void(0)"
class="button {{modal.confirmButtonClass}}" v-touch:tap="submit">{{modal.confirmButtonText}}</a>
</slot>
</div>
</div>
</div>
</div>
<div v-show="show" class="modal-backup" transition="fade"></div>
</template>
結構分為頭部、內容區、操作區三塊,每一塊都開了 slot,可按需客製。
.modal {
position: fixed;
left: 0; top: 0; right: 0; bottom: 0;
z-index: 1001;
-webkit-overflow-scrolling: touch;
outline: 0;
overflow: scroll;
margin: 30/@rate auto;
}
.modal-dialog {
position: absolute;
left: 50%;
top: 0;
transform: translate(-50%,0);
width: 690/@rate;
padding: 50/@rate 40/@rate;
background: #fff;
}
.modal-backup {
position: fixed;
top: 0; right: 0; bottom: 0; left: 0;
z-index: 1000;
background: rgba(0, 0, 0, 0.5);
}
都是常規做法。這個項目在行動端,採用淘寶的自適應方案,@rate 是切稿時的換算比例。
/**
* modal 模態接口參數
* @param {string} modal.title 模態框標題
* @param {string} modal.text 模態框內容
* @param {boolean} modal.showCancelButton 是否顯示取消按鈕
* @param {string} modal.cancelButtonClass 取消按鈕樣式
* @param {string} modal.cancelButtonText 取消按鈕文字
* @param {boolean} modal.showConfirmButton 是否顯示確定按鈕
* @param {string} modal.confirmButtonClass 確定按鈕樣式
* @param {string} modal.confirmButtonText 確定按鈕文字
*/
props: ['modalOptions'],
computed: {
/** 格式化傳入的參數,賦予默認值 */
modal: {
get() {
let modal = this.modalOptions;
modal = {
title: modal.title || '提示',
text: modal.text,
showCancelButton: typeof modal.showCancelButton === 'undefined' ? true : modal.showCancelButton,
cancelButtonClass: modal.cancelButtonClass ? modal.showCancelButton : 'btn-default',
cancelButtonText: modal.cancelButtonText ? modal.cancelButtonText : '取消',
showConfirmButton: typeof modal.showConfirmButton === 'undefined' ? true : modal.cancelButtonClass,
confirmButtonClass: modal.confirmButtonClass ? modal.confirmButtonClass : 'btn-active',
confirmButtonText: modal.confirmButtonText ? modal.confirmButtonText : '確定',
};
return modal;
},
},
},
用 computed 統一處理默認值,呼叫方只需要傳真正關心的欄位。
data() {
return {
show: false, // 是否顯示模態框
resolve: '',
reject: '',
promise: '' // 保存 promise 對象
};
},
methods: {
/** 確定:將 promise 斷定為完成態 */
submit() {
this.resolve('submit');
},
/**
* 關閉:將 promise 斷定為 reject 狀態
* @param type {number} 關閉方式,0 表示右上角關閉按鈕,1 表示取消按鈕
*/
close(type) {
this.show = false;
this.reject(type);
},
/** 顯示 confirm 彈出,並創建 promise 對象 */
confirm() {
this.show = true;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
return this.promise; // 返回 promise,供父級組件調用
},
},
核心是 confirm():它定義在組件內部,卻是給使用方調用的。調用時建立一個 Promise 並把 resolve/reject 存進 data,之後點取消就 reject 並關閉,點確定則只 resolve、不關閉——是否關閉交由父組件的回調決定。這樣「確定後還要做非同步檢查」的場景也能自然處理。
<!-- template -->
<confirm v-ref:dialog :modal-options.sync="modal"></confirm>
<!-- methods -->
this.$refs.dialog.confirm().then(() => {
// 點擊確定的回調
callback();
this.$refs.dialog.show = false;
}).catch(() => {
// 點擊取消的回調
callback();
});
用 v-ref 建立索引,就能直接拿到組件內部方法,鏈式表達非常直觀。
同事在上一個項目用的方案。先在根組件接收轉發事件,再廣播出去:
events: {
/**
* 轉發事件
* @param {string} eventName 事件名稱
* @param {object} arg 事件參數
*/
'transmit': function (eventName, arg) {
this.$broadcast(eventName, arg);
}
},
模態框組件接收事件名並在點擊時派發:
// 接收事件,獲得確定與取消按鈕要觸發的事件名
events: {
'tip': function(obj) {
this.events = {
cancel: obj.events.cancel,
confirm: obj.events.confirm
}
}
}
// 取消按鈕
cancel: function() {
this.$dispatch('transmit', this.events.cancel);
}
// 確定按鈕
submit: function() {
this.$dispatch('transmit', this.events.submit);
}
父組件調用:
this.$dispatch('transmit','tip',{ events: { confirm: 'confirmEvent' } });
this.$once('confirmEvent', function() {
callback();
});
先傳事件名進去,再用 $once 監聽,觸發後回調。能跑,但事件在組件樹中來回穿梭,追蹤起來頗費力——這也是 Vue 2.0 移除 $dispatch 與 $broadcast 的原因。我們雖然還在用 1.0,也已不再使用它們,方便日後升級。
點擊時直接 emit 事件,父組件在標籤上監聽,事件鏈路一目了然:
// 確定按鈕
ok () {
this.$emit('ok');
if (this.closeWhenOK) {
this.show = false;
}
},
// 取消按鈕
cancel () {
this.$emit('cancel');
this.show = false;
},
<modal title="Modal Title" :show.sync="show" @ok="ok" @cancel="cancel"> Modal Text </modal>
缺點也很實際:同一個組件內若有多個對話框,僅文字與回調不同,就得在模板裡重複寫好幾遍標籤,顯得囉嗦。這正是我最終選擇 Promise 方案的原因——呼叫處只是一個方法調用,參數可傳、回調可鏈。
參考資料:vue.js dynamic create nest modal、ES6 Promise 對象、vue-bootstrap-modal。