//1、在data中声明变量
data () {
return {
nowDate: null, // 存放年月日变量
nowTimer: '' // 时间定时器
}
},
//2、定义获取时间的方法getTime,并在created()声明周期里面调用,在实例创建前调用
created()
{
this.nowTimer = setInterval(this.getTime, 1000) // 定时获取当前时间
},
//3、具体方法如下:
methods: {
getTime () {
const date = new Date()
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
if (this.hour > 12) {
this.hour -= 12
}
this.month = check(month)
this.day = check(day)
this.hour = check(hour)
this.minute = check(minute)
this.second = check(second)
function check (i) {
const num = (i < 10) ? ('0' + i) : i
return num
}
this.nowDate = year + '年' + this.month + '月' + this.day + '日 ' + this.hour + ':' + this.minute + ':' + this.second
}
},
//4、离开页面使用beforeDestroy() 销毁
beforeDestroy() {
if (this.nowTimer) {
clearInterval(this.nowTimer); // 在Vue实例销毁前,清除定时器
}
}