当我们想要在vue中实时的获取最新的时间,可以使用下面的方法:
<script>
export default {
data() {
return {
timer: "",
currentTime:
new Date().getFullYear() +
"-" +
new Date().getMonth() +
1 +
"-" +
new Date().getDate() +
" " +
new Date().getHours() +
":" +
new Date().getMinutes() +
":" +
new Date().getSeconds(),
}
},
created() {
var vm = this
vm.timer = setInterval(() => {
var y = new Date().getFullYear()
var m = vm.appendZero(new Date().getMonth() + 1)
var d = vm.appendZero(new Date().getDate())
var ho = vm.appendZero(new Date().getHours())
var mi = vm.appendZero(new Date().getMinutes())
var se = vm.appendZero(new Date().getSeconds())
vm.currentTime = y + "-" + m + "-" + d + " " + ho + ":" + mi + ":" + se
}, 1000)
},
methods: {
appendZero(obj) {
if (obj < 10) {
return "0" + obj
} else {
return obj
}
},
},
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer)
}
},
}
</script>
然后再模板中使用:
|