uniapp公共弹窗
实现公共弹窗的方法
在UniApp中实现公共弹窗可以通过组件化开发方式,将弹窗封装为全局组件,方便多处调用。
创建公共弹窗组件
在components目录下新建common-popup.vue文件,编写弹窗模板和逻辑:

<template>
<view class="popup-mask" v-if="visible" @click="close">
<view class="popup-content" @click.stop>
<slot></slot>
<button @click="close">关闭</button>
</view>
</view>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit('update:visible', false)
}
}
}
</script>
<style>
.popup-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;
}
.popup-content {
background: #fff;
padding: 20px;
border-radius: 10px;
width: 80%;
}
</style>
全局注册组件
在main.js中全局注册组件:
import commonPopup from '@/components/common-popup.vue'
Vue.component('common-popup', commonPopup)
使用公共弹窗
在页面中引入并使用弹窗组件:

<template>
<view>
<button @click="showPopup = true">显示弹窗</button>
<common-popup :visible.sync="showPopup">
<view>这里是弹窗内容</view>
</common-popup>
</view>
</template>
<script>
export default {
data() {
return {
showPopup: false
}
}
}
</script>
扩展功能
支持不同弹窗类型
可以在组件中添加type属性,根据不同类型显示不同样式:
<template>
<view class="popup-mask" v-if="visible" @click="close">
<view :class="['popup-content', type]">
<slot></slot>
<button @click="close">关闭</button>
</view>
</view>
</template>
<script>
export default {
props: {
type: {
type: String,
default: 'default' // 支持default/warning/error等类型
}
}
}
</script>
<style>
.popup-content.warning {
border-left: 5px solid #f0ad4e;
}
.popup-content.error {
border-left: 5px solid #d9534f;
}
</style>
支持动画效果 添加过渡动画增强用户体验:
<template>
<view>
<view class="popup-mask" v-if="visible" @click="close">
<view class="popup-content" :class="{ 'popup-show': visible }" @click.stop>
<slot></slot>
</view>
</view>
</view>
</template>
<style>
.popup-content {
transform: scale(0.8);
opacity: 0;
transition: all 0.3s ease;
}
.popup-show {
transform: scale(1);
opacity: 1;
}
</style>
注意事项
- 弹窗内容使用
slot插槽实现高度自定义 - 点击遮罩层关闭弹窗时注意阻止事件冒泡
- 在iOS设备上可能出现滚动穿透问题,需要额外处理
- 多端兼容性问题需要测试各平台表现
通过这种方式封装的公共弹窗组件,可以在整个UniApp项目中复用,保持统一的UI风格和交互体验。






