uniapp自定义模态框cxx
时间: 2025-03-03 09:39:29 浏览: 47
### 如何在 UniApp 中创建自定义样式或功能的模态框组件
#### 创建基础项目结构
为了在 UniApp 中实现自定义样式的模态框,首先需要设置好项目的目录结构并引入必要的依赖库。
```bash
uni create my-project
cd my-project
npm install vant-weapp --save
```
#### 编写模态框组件代码
接下来,在 `components` 文件夹下新建一个名为 `CustomModal.vue` 的文件来封装自定义模态框逻辑:
```vue
<template>
<div class="custom-modal">
<!-- 遮罩层 -->
<view v-if="visible" @click.self="handleClose" class="modal-mask"></view>
<!-- 模态框主体 -->
<transition name="fade">
<view v-show="visible" class="modal-content">
<slot></slot> <!-- 插槽用于放置具体的内容 -->
<!-- 关闭按钮 -->
<button type="default" size="mini" plain round @click="handleClose">关闭</button>
</view>
</transition>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const props = defineProps({
visible: {
type: Boolean,
default: false
}
});
// 定义事件发射器
const emit = defineEmits(['update:visible']);
function handleClose() {
emit('update:visible', false);
}
</script>
<style scoped>
.custom-modal .modal-mask {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
width: 80%;
max-width: 375px;
margin: auto;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 6px rgba(0, 0, 0, 0.1);
text-align: center;
z-index: 999;
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: white;
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease-in-out;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
```
#### 使用自定义模态框组件
最后一步是在页面中注册并调用这个新创建好的组件。可以在任意 `.vue` 页面内通过如下方式完成操作:
```html
<!-- pages/index/index.vue -->
<template>
<view>
<button @click="toggleVisible(true)">打开模态框</button>
<CustomModal :visible.sync="isVisible">
这里可以放入任何想要展示给用户的提示信息或其他内容...
</CustomModal>
</view>
</template>
<script setup lang="ts">
import CustomModal from '@/components/CustomModal.vue';
import { ref } from 'vue';
let isVisible = ref(false);
function toggleVisible(flag?: boolean) {
if (flag !== undefined) {
isVisible.value = flag;
} else {
isVisible.value = !isVisible.value;
}
}
</script>
```
上述过程展示了如何基于 Vue 和 Vant WeApp 组件库构建具有特定外观和行为模式对话框的方法[^1]。
阅读全文
相关推荐


















