uniapp模态弹窗
uniapp模态弹窗实现方法
在uniapp中实现模态弹窗可以通过官方组件或第三方插件完成,以下是几种常见方法:
使用uni.showModal API
uni.showModal({
title: '提示',
content: '这是一个模态弹窗',
showCancel: true,
cancelText: '取消',
confirmText: '确定',
success: function (res) {
if (res.confirm) {
console.log('用户点击确定');
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
使用uni-popup组件 需要先安装uni-popup组件:
- 在项目中引入uni-popup
- 在页面中使用组件
<uni-popup ref="popup" type="dialog"> <uni-popup-dialog mode="base" title="标题" content="内容" @confirm="confirm" @close="close"></uni-popup-dialog> </uni-popup>methods: { openPopup() { this.$refs.popup.open(); }, confirm() { console.log('确认'); this.$refs.popup.close(); }, close() { this.$refs.popup.close(); } }
自定义弹窗组件
- 创建自定义组件
<template> <view class="modal-mask" v-if="visible" @click="close"> <view class="modal-content" @click.stop> <slot></slot> <button @click="close">关闭</button> </view> </view> </template> - 添加样式
.modal-mask { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; } .modal-content { background-color: #fff; padding: 20px; border-radius: 5px; }
使用uView UI库的模态框
- 安装uView UI
- 使用组件
<u-modal v-model="show" :title="title" :content="content"></u-modal>data() { return { show: false, title: '提示', content: '这是uView模态框' } }, methods: { openModal() { this.show = true; } }
注意事项
- 模态弹窗会阻止用户与其他页面元素交互,适合重要操作确认
- 在H5端注意z-index层级问题,避免被其他元素覆盖
- 移动端考虑弹窗大小和位置适配不同屏幕
- 复杂弹窗内容建议使用自定义组件方式实现







