这次需要写一个弹出层dialog,有确认和取消按钮的那种。
先看下弹出层的效果吧~
其实我是写成深黑透明底的,可能因为我在mac本上截的图,跟我在 windows里做出的效果不太一样,不过也是好看的。
一、src/components/messagebox下新建messagebox.js
import messageBoxVue from './messageBox.vue'
// 定义插件对象
const MessageBox = {
};
// vue的install方法,用于定义vue插件
MessageBox.install = function (Vue, options) {
const MessageBoxInstance = Vue.extend(messageBoxVue);
let currentMsg;
const initInstance = () => {
// 实例化vue实例
currentMsg = new MessageBoxInstance();
let msgBoxEl = currentMsg.$mount().$el;
document.body.appendChild(msgBoxEl);
};
// 在Vue的原型上添加实例方法,以全局调用
Vue.prototype.$messageBox = {
showMsgBox (options) {
if (!currentMsg) {
initInstance();
}
if (typeof options === 'string') {
currentMsg.content = options;
} else if (typeof options === 'object') {
Object.assign(currentMsg, options);
}
return currentMsg.showMsgBox()
.then(val => {
currentMsg = null;
return Promise.resolve(val);
})
.catch(err => {
currentMsg = null;
return Promise.reject(err);
});
}
};
};
export default MessageBox;
二、src/components/messagebox下新建messagebox.vue
<template>
<div>
<div class="msgBox" v-show="isShowMessageBox">
<div class="msgBox_header">
<div class="msgBox_title">
<h3>{
{
title }}</h3>
</div>
</div>
<div class="msgBox_content">
<p>{
{
content }}</p>
</div>
<div class="msgBox_btns">
<div class="btn btn-lime btn-lg" @click="confirm">确定</div>
<div class="btn btn-dark btn-lg" @click="cancel">取消</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'messageBox',
data(){
return {
title: '',
content: '',
isShowMessageBox: false,
resolve: '',
reject: '',
promise: '' // 保存promise对象
}
},
methods: {
close(state){
this.model.show = false;
if(this.model.callback){
this.model.callback(state);
}
},
// 确定,将promise断定为resolve状态
confirm: function () {
this.isShowMessageBox = false;
if (this.isShowInput) {
this.resolve(this.inputValue);
} else {
this.resolve('confirm');
}
this.remove();
},
// 取消,将promise断定为reject状态
cancel: function () {
this.isShowMessageBox = false;
this.reject('cancel');
this.remove();
},
// 弹出messageBox,并创建promise对象
showMsgBox: function () {
this.isShowMessageBox = true;
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
// 返回promise对象
return this.promise;
},
remove: function () {
setTimeout(() => {
this.destroy();
}, 300);
},
destroy: