uniapp 设置弹窗
使用 uni.showModal 创建基础弹窗
uni.showModal 是 Uniapp 提供的标准弹窗 API,支持标题、内容、确认和取消按钮的配置。
uni.showModal({
title: '提示',
content: '确认执行此操作吗?',
success(res) {
if (res.confirm) {
console.log('用户点击确认');
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
参数说明:
title:弹窗标题(可选)。content:弹窗内容(必填)。showCancel:是否显示取消按钮(默认true)。confirmText/cancelText:自定义按钮文字。
自定义弹窗组件
通过 Vue 组件实现高度自定义的弹窗样式和逻辑。
步骤 1:创建组件
新建 components/custom-modal.vue 文件:

<template>
<view v-if="visible" class="modal-mask">
<view class="modal-content">
<slot name="header"></slot>
<slot name="body"></slot>
<view class="modal-footer">
<button @click="onCancel">取消</button>
<button @click="onConfirm">确认</button>
</view>
</view>
</view>
</template>
<script>
export default {
props: {
visible: Boolean
},
methods: {
onConfirm() {
this.$emit('confirm');
},
onCancel() {
this.$emit('cancel');
}
}
};
</script>
<style>
.modal-mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background: #fff;
padding: 20px;
border-radius: 8px;
width: 80%;
}
</style>
步骤 2:在页面中使用
<template>
<view>
<button @click="showModal = true">打开弹窗</button>
<custom-modal :visible="showModal" @confirm="handleConfirm" @cancel="showModal = false">
<template #header>
<text>自定义标题</text>
</template>
<template #body>
<text>这里是自定义内容</text>
</template>
</custom-modal>
</view>
</template>
<script>
import CustomModal from '@/components/custom-modal.vue';
export default {
components: { CustomModal },
data() {
return {
showModal: false
};
},
methods: {
handleConfirm() {
console.log('确认操作');
this.showModal = false;
}
}
};
</script>
使用第三方组件库(如 uView UI)
uView UI 提供了丰富的弹窗组件,简化开发流程。

安装 uView UI
npm install uview-ui
配置 main.js
import uView from 'uview-ui';
Vue.use(uView);
使用弹窗组件
<template>
<view>
<u-button @click="showUViewModal">uView 弹窗</u-button>
<u-modal v-model="showModal" :title="标题" @confirm="confirmCallback">
<text>这里是内容区域</text>
</u-modal>
</view>
</template>
<script>
export default {
data() {
return {
showModal: false
};
},
methods: {
showUViewModal() {
this.showModal = true;
},
confirmCallback() {
console.log('点击确认');
}
}
};
</script>
注意事项
- 性能优化:频繁触发的弹窗建议使用组件而非
uni.showModal,减少渲染开销。 - 多端兼容:自定义组件需测试各平台(H5、小程序、App)的样式兼容性。
- 遮罩层点击关闭:可通过监听遮罩层点击事件关闭弹窗,增强用户体验。






