最近在做项目时,多个项目都有这个需求,动态显示实时时间,所以我就把它整理在这
原本我是想用监听器来实现这个动态变化,但是发现总的有东西来触发时间变变化,所以使用了定时器,每次过一秒就重新调用Date()来获取时间,然后在这个界面销毁时,清除定时器(必须清除,不然那定时器一直会存在消耗性能)
<template>
<view class="content">
<image src="../../static/clock.png"></image>
<view class="time">{{date}}</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello',
date:'',
setTime:''
}
},
onLoad() {
var setTime = setInterval( ()=> {
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth() + 1
month >= 9 ? month : month='0'+month
let day = date.getDate()
day >= 9 ? day : day = '0'+ day
let hour = date.getHours()
hour >= 9 ? hour : hour = '0'+hour
let minute = date.getMinutes()
minute >= 9 ? minute : minute = '0'+minute
let second = date.getSeconds()
second >= 9 ? second : second = '0'+second
this.date = year + '-'+month+'-'+day+" "+hour+":"+minute+":"+second
}, 1000)
},
onHide(){
clearInterval(setTime)
},
methods: {
}
}
</script>
<style lang="scss">
.content {
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
image{
height: 300rpx;
width: 300rpx;
}
.time{
font-size: 40rpx;
font-weight: bold;
font-family: 'Courier New', Courier, monospace;
}
}
</style>