uniapp公共弹窗
实现全局弹窗组件
在uniapp中实现公共弹窗可以通过自定义组件方式完成。创建一个全局组件,在需要的地方调用。
创建components/popup/popup.vue文件:
<template>
<view class="popup-mask" v-if="show" @click="close">
<view class="popup-content" @click.stop>
<slot></slot>
</view>
</view>
</template>
<script>
export default {
props: {
show: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit('update:show', 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;
z-index: 999;
}
.popup-content {
background-color: #fff;
border-radius: 10rpx;
padding: 30rpx;
width: 80%;
}
</style>
全局注册组件
在main.js中全局注册组件:
import Vue from 'vue'
import popup from '@/components/popup/popup.vue'
Vue.component('popup', popup)
页面中使用弹窗
在任何页面中可以直接使用:
<template>
<view>
<button @click="showPopup = true">打开弹窗</button>
<popup :show.sync="showPopup">
<view>这里是弹窗内容</view>
<button @click="showPopup = false">关闭</button>
</popup>
</view>
</template>
<script>
export default {
data() {
return {
showPopup: false
}
}
}
</script>
通过Vuex管理弹窗状态
对于复杂应用,可以使用Vuex集中管理弹窗状态:
// store.js
export default new Vuex.Store({
state: {
popupVisible: false,
popupContent: ''
},
mutations: {
showPopup(state, content) {
state.popupVisible = true
state.popupContent = content
},
hidePopup(state) {
state.popupVisible = false
}
}
})
通过方法调用弹窗
创建全局弹窗服务:
// utils/popup.js
export default {
show(content) {
uni.$emit('showPopup', content)
},
hide() {
uni.$emit('hidePopup')
}
}
在App.vue中监听:
<script>
export default {
created() {
uni.$on('showPopup', (content) => {
this.$store.commit('showPopup', content)
})
uni.$on('hidePopup', () => {
this.$store.commit('hidePopup')
})
}
}
</script>
使用时直接调用:
import popup from '@/utils/popup.js'
popup.show('自定义内容')
// 关闭
popup.hide()
注意事项
组件样式需要根据实际需求调整,包括动画效果、位置等。对于多弹窗场景,可以扩展组件支持不同类型弹窗。弹窗内容可以通过插槽或props灵活传递。







