主页面wxml
//wx:if="{{isCreted}}"倒计时结束后移除这个组件
//bindevent="handelEvent" 倒计时为0时,子组件通过事件通知父组件
<view>倒计时:</view>
<count wx:if="{{isCreted}}" bindevent="handelEvent"></count>
在主页面的json文件中引用
"usingComponents": {
"count":"../../component/count/Count"
}
主页面js
data: {
isCreted:true
},
handelEvent(){
this.setData({
isCreted:false
})
},
子组件wxml
<view>{{count}}</view>
子组件的js
Component({
lifetimes: {
// 在组件实例进入页面节点树时执行
attached:function(){
this.setIntervalId = setInterval(()=>{
if(this.data.count === 0){
this.triggerEvent('event')//通过事件通知父组件
return
}
this.setData({
count:this.data.count-1
})
},1000)
},
detached: function() {
// 在组件实例被从页面节点树移除时执行
clearInterval(this.setIntervalId)//清除定时器
},
},
data: {
count:10
},
})