自定义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方法关闭模态框。

相关推荐
JavaGuide2 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang02172 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户69371750013842 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk81632 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen3 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试
jerrywus3 小时前
15 个可以直接安装的 AI Agent Skills:按场景挑
前端·agent·claude
涛涛ing3 小时前
用了三年微前端,我们终于把它拆成了单体应用
前端
去伪存真4 小时前
《最终版》《打死不改版》全传一遍?RAG 系统文件去重实战
前端
anyup4 小时前
【全端支持】 uni-app x 专用请求库:axios 写法,多实例、拦截器、可中断、上传下载
前端·uni-app·unix
费曼学习法4 小时前
6 个 MCP Server 传输层重写实录:超时率 12% → 0.3%
前端·后端