1.html中
<div class="dev_time">{{ nowDate }}</div>
2.data中定义
data() {
return {
nowDate: ''
}
}
3.在methods中定义转化时间戳的函数并添加定时器
// 获取时间
currentTime () {
setInterval(this.formatDate, 500)
},
formatDate () {
let time = new Date()
let year = time.getFullYear()
const month = (time.getMonth() + 1).toString().padStart(2,'0')
const date = (time.getDate()).toString().padStart(2,'0')
const hours = (time.getHours()).toString().padStart(2,'0')
const minute = (time.getMinutes()).toString().padStart(2,'0')
const second = (time.getSeconds()).toString().padStart(2,'0')
this.nowDate = year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}
4.在生命周期函数mounted中执行定时器函数
mounted () {
this.currentTime()
}
5.在生命周期函数beforeDestroy函数中清除定时器
beforeDestroy () {
if (this.formatDate) {
clearInterval(this.formatDate) // 在Vue实例销毁前,清除时间定时器
}
}
本文只作为个人学习记录......