微信小程序 自定义组件实现类似Modal的弹框

效果展示:

思路:

在项目中,我们会遇到这样的情况,以上的的弹框都是类似的,我们不需要每个页面都写个弹框+背景。这样很是麻烦和繁琐。

不如我们拆分成这样,弹框(组件)+弹框内容(slot)。 

组件代码:

.wxml:

<!-- 弹框组件,类似 Modal -->
<block wx:if="{{isShowInvite}}">
  <cover-view class="alert_bg" bindtap="_alertClose"></cover-view>
  <cover-view class="alert_invite_wrap">
    <cover-view class="alert_invite">
      <cover-view class="alert_invite_tit">{{title}}</cover-view>
      <slot name="rules"></slot>
      <slot name="twobutton"></slot>
      <cover-view class="bottom_tit">{{bottomTxt}}</cover-view>
    </cover-view>
    <cover-image src="{{iconClose}}" class="icon_close" bindtap="_alertClose"></cover-image>
  </cover-view>
</block>

.wxss:

.alert_bg{
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0,0,0,.8);
  z-index: 99999;
}
.alert_invite_wrap{
  width: 80%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  z-index: 999999;
}
.alert_invite{
  width: 100%;
  background-color: #fff;
  border-radius: 20rpx;
  padding:50rpx;
  box-sizing: border-box;
  overflow: initial;
}
/* .alert_invite_txt{
  width: 100%;
  font-size: 26rpx;
  color: #444444;
  line-height: 25px;
  white-space: pre-wrap;
  margin-bottom: 75rpx;
} */
.alert_invite_tit{
  font-weight: bold;
  font-size: 40rpx;
  color: #333333;
  margin-bottom: 55rpx;
}
.invite_btn{
  width: 100%!important;
  height: 80rpx;
  box-sizing: border-box;
  line-height: 80rpx;
  background: #ffcc21;
  border-radius: 50rpx;
  font-size: 30rpx;
  color: #444444;
}
.icon_close{
  width: 80rpx;
  height: 80rpx;
  margin:0 auto;
  margin-top: 80rpx;
}
.bottom_tit{
  font-size: 26rpx;
  color: #444444;
  text-align: center;
}

.js:

Component({
  data: {
    iconClose: 'http://39.105.134.221:8080/test/source1.png' //需要后端将icon_close_white放在服务器上,这个暂时用播放的
  },
  options:{
    multipleSlots: true
  },
  properties: {
    title: {
      type: String,
      value: '邀请获下载券'
    },
    isShowInvite: {
      type: Boolean,
      value: false
    },
    bottomTxt:{
      type:String,
      value:''
    },
  },
  methods: {
    _alertClose() {
      this.setData({
        isShowInvite: false
      })
    }
  }
})

pages页面使用该组件:

<alert-invite-rules id="inviteRules" title="没有下载券了" isShowInvite="{{isShowInvite}}">
    <view slot="rules">
      <view class="alert_invite_txt">{{couponTxt}}</view>
    </view>
    <view slot="twobutton">
      <button class="invite_btn" style="bottom:20px" hover-class="none">¥1买整套</button>
      <button class="invite_btn invite_btn_gray" hover-class="none" open-type="share">邀请获券</button>
    </view>
  </alert-invite-rules>

嗯嗯....

以上pages页面里面的<alert-invite-rules></alert-invite-rules>  就直接可以完成  弹框 + 弹框内容。这样就简洁了好多。

发布了270 篇原创文章 · 获赞 50 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/Miss_liangrm/article/details/104040680