小程序P182 20.登录与支付-三秒跳转-初步实现三秒倒计时跳转的功能
①在 my-settle 组件的 methods 节点中,声明一个叫做 showTips 的方法,专门用来展示倒计时的提示消息:
// 展示倒计时的提示消息
showTips(n) {
uni.showToast({
// 不展示任何图标
icon: 'none',
// 提示的消息
title: '请登录后再结算!' + n + ' 秒后自动跳转到登录页',
// 为页面添加透明遮罩,防止点击穿透
mask: true,
// 1.5 秒后自动消失
duration: 1500
})
}
②在 data 节点中声明倒计时的秒数:
data() {
return {
seconds: 3
}
}
③改造 结算 按钮的 click 事件处理函数,如果用户没有登录,则预调用一个叫做 delayNavigate 的方法,进行倒计时的导航跳转:
// 点击了结算按钮
settlement() {
if (!this.checkedCount) return uni.$showMsg('请选择要结算的商品!')
if (!this.addstr) return uni.$showMsg('请选择收货地址!')
// if (!this.token) return uni.$showMsg('请先登录!')
if (!this.token) return this.delayNavigate()
},
定义 delayNavigate 方法,初步实现倒计时的提示功能:
// 延迟导航到 my 页面
delayNavigate() {
// 1. 展示提示消息,此时 seconds 的值等于 3
this.showTips(this.seconds)
// 2. 创建定时器,每隔 1 秒执行一次
setInterval(() => {
// 2.1 先让秒数自减 1
this.seconds--
// 2.2 再根据最新的秒数,进行消息提示
this.showTips(this.seconds)
}, 1000)
},