自定义modal模态框

在uni-app中,通过自定义组件和组件扩展来实现自定义的模态框Modal组件。

  1. 创建自定义组件:

在uni-app项目中,创建一个自定义的模态框组件。在components文件夹下创建一个名为CustomModal的文件夹,并在其中创建CustomModal.vue文件。在该文件中定义模态框的布局和样式,例如:

复制代码
<template>  
    <view class="custom-modal" v-if="visible">  
       <!-- 模态框的内容 -->  
       <view class="content">  
         <slot></slot>  
       </view>  
     </view>  
 </template>  
     
 <script>  
   export default {  
     props: {  
       visible: {  
         type: Boolean,  
         default: false  
       }  
     }  
   };  
  </script>  
 
  <style scoped>  
   .custom-modal {  
     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;  
   }  
     
   .custom-modal .content {  
     width: 80%;  
     background-color: #fff;  
     padding: 20px;  
     border-radius: 10px;  
   }  
  </style>  

模态框组件默认是隐藏的(visible属性默认为false),当visible属性为true时,模态框显示。可以在content元素中放置模态框的内容,通过插槽(slot)的方式实现。

  1. 在需要使用模态框的页面中引入和使用自定义组件:

在需要显示模态框的页面中,引入和使用刚才创建的自定义模态框组件。例如,在pages文件夹下的home页面中,可以添加以下代码:

复制代码
 <template>  
     <view>  
       <!-- 页面内容... -->  
       <button @click="openModal">打开模态框</button>  
       <!-- 引入自定义模态框 -->  
       <custom-modal :visible="modalVisible">  
         <!-- 模态框的内容 -->  
         <view>  
           <text>这是一个自定义模态框</text>  
           <button @click="closeModal">关闭</button>  
         </view>  
       </custom-modal>  
     </view>  
   </template>  
     
   <script>  
   import CustomModal from "@/components/CustomModal";  
     
   export default {  
     components: {  
       CustomModal  
     },  
     data() {  
       return {  
         modalVisible: false  
       };  
     },  
     methods: {  
       openModal() {  
         // 打开模态框  
         this.modalVisible = true;  
       },  
       closeModal() {  
         // 关闭模态框  
         this.modalVisible = false;  
       }  
     }  
   };  
   </script>  

在页面中引入了创建的自定义组件CustomModal,并通过modalVisible属性控制模态框的显示和隐藏。点击"打开模态框"按钮时,调用openModal方法打开模态框,点击模态框内的"关闭"按钮时,调用closeModal方法关闭模态框。

相关推荐
Highcharts.js15 分钟前
React 中原生支持使用 JSX 组件配置自定义表格 Highcharts Grid
前端·javascript·react.js·前端框架·jsx·highcharts·自定义表格
Java后端的Ai之路21 分钟前
【AIAgent开发】-Agent工具封装成CLI(纯干货!!!)
java·javascript·人工智能·agent·cli
薛定谔的猫-菜鸟程序员39 分钟前
Electron开发超详细教程(从入门到放弃)
前端·javascript·electron
最强小杰1 小时前
DeepSeek V4 Flash + Codex CLI 接入教程:原生 Responses API 适配,从配置到跑通收藏这篇就够了(2026)
java·前端·python·ai
静水leo1 小时前
使用 Whistle 拦截接口并模拟后端响应
前端
掘金者阿豪2 小时前
SQL Server数据迁移完成后,凌晨的数据库告警该怎么查?
前端·后端
JudithHuang2 小时前
React 嵌套路由与布局
前端·react.js·arcgis·react·react router
啾咪orJIUMI2 小时前
Vue 3 + SCSS 实现全屏系统门户:五栏展开与灯光联动
css
htzyl2062 小时前
前端阶梯——第四十三章、实战二:待办清单To-Do
前端·javascript·html