需求:一个原生页活动专题,从专题页进去商详页,实现用户返回退出商详页时发放优惠券,即弹出优惠券弹窗。
用小程序原生组件page-container来实现, 官方文档:developers.weixin.qq.com/miniprogram…
idnex页面好比商详页,从上一级跳转进来的,可以返回。
思路:如果符合弹窗条件,show为true,组件一直存在页面中。初始showModal值为false,组件display为none,并不显示。当用户有返回行为时,即触发了组件的beforeleave事件(其实在离开组件时还会触发离开中、离开后事件,选择离开前进行显示弹窗操作较为合适),在事件中设置两个变量都为true,即显示组件。
遇到的问题:本人在将次逻辑运用于实际业务代码中时,在未触发返回操作,组件一直未显示时,会无法滚动页面,因为整个Page会被自动加上样式style="position:fixed;top:0px;",导致页面无法滚动。我的解决方案是:在wxss中给Page加如下样式,不让它fixed。但在demo中并没有出现这个问题。
Page{
position: relative !important;
top: 0px !important;
}
Demo代码如下:
index.wxml
<scroll-view scroll-y style="height: 100vh;">
<view style="width: 100vw;height: 900rpx;background-color: bisque;"></view>
<view style="width: 100vw;height: 900rpx;background-color: cyan;"></view>
</scroll-view>
<view wx:if="{{show}}">
<page-container
show="{{show}}"
round="{{round}}"
duration="{{duration}}"
position="{{position}}"
close-on-slide-down="{{false}}"
bindbeforeleave="onBeforeLeave"
custom-style="display:{{showModal ? 'block' : 'none'}};width: 100vw; height: 100vh; "
overlay="{{false}}"
>
<view class="detail-page">
<button type="primary" bindtap="exit">推出</button>
</view>
</page-container>
</view>
index.js
Page({
data: {
show: true,
duration: 300,
position: 'center',
round: false,
overlay: true,
showModal: false,
},
onShow() {
},
exit() {
this.setData({
show: false,
showModal: false,
})
},
onBeforeLeave(res) {
console.log(res)
if(this.data.show){
this.setData({
showModal: true,
show: true,
})
}
},
})
index.wxss
.detail-page {
width: 100%;
height: 100%;
min-height: 300px;
display: flex;
align-items: center;
justify-content: center;
}