微信小程序自定义组件弹出框
2022-12-14 本文已影响0人
hao_developer



需求:点击‘弹出框’按钮,显示弹出框,如果在不点击的情况下,会在2s后自动消失(可自定义),点击弹出框任何部位都会消失
思路:不能在组件中进行修改isShow的值,需要把点击事件传到view中,在view中进行修改赋值,最后在通过自定义属性isShow进行传递,来进行控制是否显示弹出框

组件---wxml
<view wx:if="{{isShow}}" class="tip-area">
<view bindtap="hideClick" class="dialog-content">
<view class="tip-content">
{{contentStr}}
</view>
<view class="btn-content">
{{btnStr}}
</view>
</view>
</view>
组件---wxss
.tip-area {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, .5);
}
.dialog-content{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 60vw;
height: auto;
display: flex;
flex-direction: column;
}
.tip-content {
background: white;
width: 60vw;
height: 34vw;
border-radius: 20rpx 20rpx 0 0;
box-sizing: border-box;
line-height: 34vw;
text-align: center;
font-size: 30rpx;
color: black;
border-bottom: .5rpx solid #e8e8e9;
}
.btn-content{
width: 100%;
height: 10vw;
border-radius: 0 0 20rpx 20rpx;
background: white;
text-align: center;
line-height: 10vw;
font-size: 32rpx;
}
组件---js
Component({
properties: {
isShow: {//false:弹出框消息 true:弹出框显示
value: false,
type: Boolean
},
contentStr:{//弹出框需要显示的内容
value: '内容',
type: String,
},
btnStr:{//按钮文本(可进行自行扩展两个按钮)
value: '确定',
type: String,
}
},
data: {
timeId: null,//弹出框消息倒计时标识
},
observers: {//监听isShow属性的变化,来进行判断是否显示弹出框
"isShow": function (value) {
clearTimeout(this.data.timeId);
if (value) {
this.data.timeId = setTimeout(() => {
this.setData({
isShow: false,
});
}, 2000);
}
}
},
methods: {
hideClick() {//点击弹出框的任意位置进行点击事件的传递,从而修改isShow的值,来控制弹出框消失
this.triggerEvent('clickDialog', {
isShow: false
});
clearTimeout(this.data.timeId);
}
},
})
使用案例
案例---json
{
"usingComponents": {
"dialog": "../../components/dialog/index"
}
}
案例---wxml
<button bindtap="showDialog" type="primary">弹出框</button>
<dialog bind:clickDialog="clickDialog" isShow="{{isShow}}" contentStr="准备好了吗?" btnStr="确定"></dialog>
案例---js
Page({
data: {
isShow: false,//true:显示弹出框 false:隐藏弹出框
},
showDialog(e){//显示弹出框
this.setData({
isShow: true,
})
},
clickDialog(e){//接受弹出框点击反馈监听事件,来进行隐藏弹出框
this.setData({
isShow: e.detail.isShow,
})
},
})