小程序P182 20.登录与支付-三秒跳转-初步实现三秒倒计时跳转的功能(接上一个)
上述代码的问题:定时器不会自动停止,此时秒数会出现等于 0 或小于 0 的情况!
⑤在 data 节点中声明定时器的 Id 如下:
data() {
return {
// 倒计时的秒数
seconds: 3,
// 定时器的 Id
timer: null
}
}
⑥改造 delayNavigate 方法如下:
// 延迟导航到 my 页面
delayNavigate() {
this.showTips(this.seconds)
// 1. 将定时器的 Id 存储到 timer 中
this.timer = setInterval(() => {
this.seconds--
// 2. 判断秒数是否 <= 0
if (this.seconds <= 0) {
clearInterval(this.timer)
uni.switchTab({
url: '/pages/my/my'
})
// 2.3 终止后续代码的运行(当秒数为 0 时,不再展示 toast 提示消息)
return
}
this.showTips(this.seconds)
}, 1000)
},
上述代码的问题:seconds 秒数不会被重置,导致第 2 次,3 次,n 次 的倒计时跳转功能无法正常工作
⑦进一步改造 delayNavigate 方法,在执行此方法时,立即将 seconds 秒数重置为 3 即可:
// 延迟导航到 my 页面
delayNavigate() {
// 把 data 中的秒数重置成 3 秒
this.seconds = 3
this.showTips(this.seconds)
this.timer = setInterval(() => {
this.seconds--
if (this.seconds <= 0) {
clearInterval(this.timer)
uni.switchTab({
url: '/pages/my/my'
})
return }
this.showTips(this.seconds)
}, 1000)
}