前言
在开发项目的过程中,经常会需要开发一些弹出框效果,但原生的alert和confirm往往都无法满足项目的要求。这次在开发基于Vue.js的读书WebApp的时候总共有两处需要进行提示的地方,因为一开始就没有引入其他的组件库,现在只好自己写一个模态框组件了。目前只是一个仅满足当前项目需求的初始版本,因为这个项目比较简单,也就没有保留很多的扩展功能。这个组件还是有很多扩展空间的,可以增加更多的自定义内容和样式。这里只介绍如何去开发一个模态框组件,有需要进行更多扩展的,可以根据自己的需求自行开发。
组件模板
<template><div class="dialog"> <div class="mask"></div> <div class="dialog-content"> <h3 class="title">{
{
modal.title }
}
</h3> <p class="text">{
{
modal.text }
}
</p> <div class="btn-group"> <div class="btn" @click="cancel">{
{
modal.cancelButtonText }
}
</div> <div class="btn" @click="submit">{
{
modal.confirmButtonText }
}
</div> </div> </div></div></template>
模态框结构分为:头部标题、提示内容和操作区域。同时一般还会有一个遮罩层。此次需求比较简单,也无需图标等内容,所以结构上写的也比较简单。实际开发中可根据需求对结构进行相应的调整。
组件样式
.dialog {
position: relative;
.dialog-content {
position: fixed;
box-sizing: border-box;
padding: 20px;
width: 80%;
min-height: 140px;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
border-radius: 5px;
background: #fff;
z-index: 50002;
.title {
font-size: 16px;
font-weight: 600;
line-height: 30px;
}
.text {
font-size: 14px;
line-height: 30px;
color: #555;
}
.btn-group {
display: flex;
position: absolute;
right: 0;
bottom: 10px;
.btn {
padding: 10px 20px;
font-size: 14px;
&:last-child {
color: #76D49B;
}
}
}
}
.mask {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 50001;
background: rgba(0,0,0,.5);
}
}
样式比较简单,就不多说了。
组件接口
export default {
name: 'dialog', props: {
dialogOption: Object }
, data() {
return {
resolve: '', reject: '', promise: '', // 保存promise对象 }
}
, computed: {
modal: function() {
let options = this.dialogOption;
return {
title: options.title || '提示', text: options.text, cancelButtonText: options.cancelButtonText ? options.cancelButtonText : '取消', confirmButtonText: options.confirmButtonText ? options.confirmButtonText : '确定', }
}
}
, methods: {
//确定,将promise断定为完成态 submit() {
this.resolve('submit');
}
, // 取消,将promise断定为reject状态 cancel() {
this.reject('cancel');
}
, //显示confirm弹出,并创建promise对象,给父组件调用 confirm() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
}
);
return this.promise;
//返回promise对象,给父级组件调用 }
}
}
在模态框组件中定义了三个方法,核心的方法是confirm,此方法是提供给父级组件调用的,返回一个promise对象。使用promise对象主要是为了异步调用,因为很多时候我们使用模态框时需要根据返回结果再进行下一步处理。
扩展提示:
如果需要扩展的话,可以通过props的dialogOption传递更多的字段,在computed中进行判断,比如增加一个字段isShowCancelButton可以控制取消按钮是否显示。其他扩展同理。
调用
<v-dialog v-show="showDialog" :dialog-option="dialogOption" ref="dialog"></v-dialog>this.showDialog = true;
this.$refs.dialog.confirm().then(() => {
this.showDialog = false;
next();
}
).catch(() => {
this.showDialog = false;
next();
}
)
源码地址
实现效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。