本篇文章主要介绍了Vue.js弹出模态框组件开发的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
前言
在开发项目的过程中,经常会需要开发一些弹出框效果,但原生的alert和confirm往往都无法满足项目的要求。这次在开发基于Vue.js的读书WebApp的时候总共有两处需要进行提示的地方,因为一开始就没有引入其他的组件库,现在只好自己写一个模态框组件了。目前只是一个仅满足当前项目需求的初始版本,因为这个项目比较简单,也就没有保留很多的扩展功能。这个组件还是有很多扩展空间的,可以增加更多的自定义内容和样式。这里只介绍如何去开发一个模态框组件,有需要进行更多扩展的,可以根据自己的需求自行开发。
组件模板
1 2 3 4 5 6 7 8 9 10 11 12 13 | <template>
<p class = "dialog" >
<p class = "mask" ></p>
<p class = "dialog-content" >
<h3 class = "title" >{{ modal.title }}</h3>
<p class = "text" >{{ modal.text }}</p>
<p class = "btn-group" >
<p class = "btn" @click= "cancel" >{{ modal.cancelButtonText }}</p>
<p class = "btn" @click= "submit" >{{ modal.confirmButtonText }}</p>
</p>
</p>
</p>
</template>
|
登录后复制
模态框结构分为:头部标题、提示内容和操作区域。同时一般还会有一个遮罩层。此次需求比较简单,也无需图标等内容,所以结构上写的也比较简单。实际开发中可根据需求对结构进行相应的调整。
组件样式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | .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);
}
}
|
登录后复制
样式比较简单,就不多说了。
组件接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | export default {
name: 'dialog',
props: {
dialogOption: Object
},
data() {
return {
resolve: '',
reject: '',
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: {
submit() {
this.resolve('submit');
},
cancel() {
this.reject('cancel');
},
confirm() {
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
return this.promise;
}
}
}
|
登录后复制
在模态框组件中定义了三个方法,核心的方法是confirm,此方法是提供给父级组件调用的,返回一个promise对象。使用promise对象主要是为了异步调用,因为很多时候我们使用模态框时需要根据返回结果再进行下一步处理。
扩展提示:
如果需要扩展的话,可以通过props的dialogOption传递更多的字段,在computed中进行判断,比如增加一个字段isShowCancelButton可以控制取消按钮是否显示。其他扩展同理。
调用
1 2 3 4 5 6 7 8 9 10 | <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();
})
|
登录后复制
源码地址
Dialog组件源码
实现效果


以上是Vue.js如何开发弹出模态框组件的方法介绍的详细内容。更多信息请关注PHP中文网其他相关文章!