首先创建一个组件component,组件命名可以为modal
modal.wxml的内容为
1<view class='modal-mask' wx:if='{{show}}' bindtap='clickMask'> 2 <view class='modal-content'> 3 <scroll-view scroll-y class='main-content'> 4 <slot></slot> 5 </scroll-view> 6 <view class='modal-footer'> 7 <view wx:if='{{!single}}' class='cancel-btn' bindtap='cancel'>取消</view> 8 <view class='confirm-btn' bindtap='confirm'>确定 </view> 9 </view> 10 </view> 11</view> 12
modal.js的内容为
1Component({ 2 /** 3 * 组件的属性列表 4 */ 5 properties: { 6 //是否显示modal弹窗 7 show: { 8 type: Boolean, 9 value: false 10 }, 11 //控制底部是一个按钮还是两个按钮,默认两个 12 single: { 13 type: Boolean, 14 value: false 15 } 16 }, 17 18 /** 19 * 组件的初始数据 20 */ 21 data: { 22 23 }, 24 25 /** 26 * 组件的方法列表 27 */ 28 methods: { 29 // 点击modal的回调函数 30 clickMask() { 31 // 点击modal背景关闭遮罩层,如果不需要注释掉即可 32 this.setData({show: false}) 33 }, 34 // 点击取消按钮的回调函数 35 cancel() { 36 this.setData({ show: false }) 37 this.triggerEvent('cancel') //triggerEvent触发事件 38 }, 39 // 点击确定按钮的回调函数 40 confirm() { 41 this.setData({ show: false }) 42 this.triggerEvent('confirm') 43 } 44 } 45}) 46
modal.wxss的内容为
1/* components/modal/modal.wxss */ 2/*遮罩层*/ 3.modal-mask{ 4 display: flex; 5 justify-content: center; 6 align-items: center; 7 position: fixed; 8 left: 0; 9 right: 0; 10 top: 0; 11 bottom: 0; 12 background-color: rgba(0,0,0,0.5); 13 z-index: 999; 14} 15/*遮罩内容*/ 16.modal-content{ 17 display: flex; 18 flex-direction: column; 19 width: 80%; 20 background-color: #fff; 21 border-radius: 10rpx; 22 padding: 20rpx; 23 text-align: center; 24} 25/*中间内容*/ 26.main-content{ 27 flex: 1; 28 height: 100%; 29 overflow-y: hidden; 30 max-height: 80vh; /* 内容高度最高80vh 以免内容太多溢出*/ 31} 32/*底部按钮*/ 33.modal-footer{ 34 display: flex; 35 flex-direction: row; 36 height: 80rpx; 37 line-height: 80rpx; 38 border-top: 2rpx solid #D2D3D5; 39 margin-top: 30rpx; 40} 41.cancel-btn, .confirm-btn{ 42 flex: 1; 43 height: 100rpx; 44 line-height: 100rpx; 45 text-align: center; 46 font-size: 32rpx; 47} 48.cancel-btn{ 49 color: #000; 50 border-right: 2rpx solid #D2D3D5; 51} 52.confirm-btn { 53 color: #3f88ea; 54} 55.title{ 56 text-align: center; 57 58} 59 60
在页面上的应用为
"modalView": "/components/modal/modal"
1 <!-- modal弹窗--> 2 <modalView show="{{!isShow}}" bindcancel="modalCancel" bindconfirm='modalConfirm' single='{{false}}'> 3 <view class='modal-content'> 4 <scroll-view scroll-y class='main-content'> 5 <view class="content"> 6 7 </view> 8 </scroll-view> 9 </view> 10 </modalView>
在data中 添加
isShow:false
显示时设置
1 this.setData({ 2 isShow:true 3 })
