uniapp 设置弹窗
设置弹窗的方法
在UniApp中设置弹窗可以使用官方提供的uni.showModal、uni.showToast等API,也可以自定义弹窗组件。
使用uni.showModal

uni.showModal({
title: '提示',
content: '这是一个模态弹窗',
success: function (res) {
if (res.confirm) {
console.log('用户点击确定');
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
使用uni.showToast
uni.showToast({
title: '操作成功',
icon: 'success',
duration: 2000
});
自定义弹窗组件
创建一个自定义弹窗组件,可以更灵活地控制弹窗的样式和行为。

创建组件
在components目录下创建custom-modal.vue文件:
<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>
<script>
export default {
props: {
visible: Boolean
},
methods: {
close() {
this.$emit('update:visible', false);
}
}
};
</script>
<style>
.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;
}
</style>
使用自定义组件 在页面中引入并使用自定义弹窗组件:
<template>
<view>
<button @click="showModal = true">打开弹窗</button>
<custom-modal :visible.sync="showModal">
<view>这是自定义弹窗内容</view>
</custom-modal>
</view>
</template>
<script>
import CustomModal from '@/components/custom-modal.vue';
export default {
components: { CustomModal },
data() {
return {
showModal: false
};
}
};
</script>
注意事项
- 使用官方API时,注意不同平台的兼容性,部分API在小程序和H5中的表现可能不同。
- 自定义弹窗组件时,确保遮罩层和内容层的样式正确,避免事件冒泡问题。
- 弹窗内容较多时,考虑使用滚动区域,避免内容溢出。





