自定义一个小程序弹窗Modal模板组件(但不限于小程序)

2022-07-26,,,,

1.前端环境: Taro + Vue 2.5+

2.全局component下建立Modal.vue文件

 3.代码结构: 

弹窗的结构很简单,  只需要三个view即可

<template>
  <view class="modal">
    <view class="wrapper">  // wrapper层可用于点击遮罩关闭弹窗交互
      <view class="content" :style="{width: width + 'px', height: height + 'px'}">  
          //content层可自定义宽高
          <slot />  // 插槽可自定义弹窗展示内容
      </view>
    </view>
  </view>
</template>

 

4.弹窗效果主要依赖于css样式

<style lang="less">
.modal {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);     // 定义遮罩的背景
  animation: modal-animate 0.1s linear;     // 定义弹窗的动画效果
  .wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .content {
    width: 700px;                           // 不传宽高就自动读取class值, 也可以不写
    height: 414px;
    background-color: #fff;
  }
  @keyframes modal-animate {               // 动画, 可自定义, 可以配置多个动画类, 通过pros动态使用
    from {
      opacity: 0;                          // 淡入淡出
      // transform: scale(0);              // 放大缩小
    }
    to {
      opacity: 1;
      // transform: scale(0);
    }
  }
}
</style>

到这里一个弹窗组件模板就建立好了

其实我们经常看到的Drawer抽屉组件, 它的书写模板也可以根据这个改造,

只需要修改动画实现方式就可以, 转换成transform: translateX()或者translateY()

至于是左滑还是右滑, 上滑还是下滑的起始位置, 可以用props动态传入

 

 

 

本文地址:https://blog.csdn.net/weixin_41457552/article/details/110638576

《自定义一个小程序弹窗Modal模板组件(但不限于小程序).doc》

下载本文的Word格式文档,以方便收藏与打印。