效果如
实现过程
js:
const app = getApp()
import util from '../../utils/util.js'
Page({
/**
* 页面的初始数据
*/
data: {
todayTime: '', // 获取当前时间
realTime: '',
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function () {
this.gettodayTime() // 获取当前时间
},
// 获取当前时间
gettodayTime(){
// 调用函数时,传入new Date()参数,返回值是时间
var time = util.formatTodayTime(new Date());
this.setData({
todayTime: time // 页面展示的时分秒数据
});
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function (options) {
var that = this
this.data.realTime = setInterval(function()
{
that.gettodayTime()
}, 1000)//间隔时间 1s
// 更新数据
this.setData({
realTime:this.data.realTime,//实时数据对象(用于关闭实时刷新方法)
})
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
/**
* 当页面隐藏时关闭定时器(关闭实时刷新)
* 切换到其他页面了
*/
clearInterval(this.data.realTime)
},
})
util.js
//展示时分秒
const formatTodayTime = date => {
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [hour, minute, second].map(formatNumber).join(':')
}
module.exports = {
formatTodayTime: formatTodayTime,
}