前言:在实际项目中,我们有时会遇到需要显示当前时间的问题,这样可以和数据实时显示相结合,使数据能够比较直观的显示出来。
一、html部分
<div class="nowDate">更新至当日{{gettime}}时</div>
二、script部分
<script>
export default {
created(){
//触发定时器,创建当前时间
this.currentTime();
},
methods: {
//获取当前时间,进行转换
getTime:function(){
var _this = this;
let hh = new Date().getHours();
_this.gettime = hh+':'+'00';
},
//创建定时器
currentTime(){
setInterval(this.getTime,500)
},
},
data() {
return{
gettime:'', //当前时间
};
},
};
</script>
三、补充内容
以上案例只显示当前的整点时间,下面补充一个完整显示时分秒的实时时间显示。
(1)获取当前时间,进行转换
getTime:function(){
var _this = this;
let yy = new Date().getFullYear();
let mm = new Date().getMonth()+1;
let dd = new Date().getDate();
let hh = new Date().getHours();
let mf = new Date().getMinutes()<10 ? '0' + new Date().getMinutes() : new Date().getMinures();
let ss = new Date().getSeconds()<10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
},
(2)创建定时器
currentTime(){
setInterval(this.getTime,500)
},
(3)在生命周期函数中触发定时器
created() {
this.currentTime();
},
<p>{{gettime}}</p>
data() {
return {
gettime: '',//当前时间
},
},
如上如有问题,欢迎留言指正,谢谢。
版权声明:本文为博主原创文章,未经博主允许不得转载 。
参考博客:https://www.jianshu.com/p/7c4a4fd6cf76