vue显示当前时间,创建定时器

前言:在实际项目中,我们有时会遇到需要显示当前时间的问题,这样可以和数据实时显示相结合,使数据能够比较直观的显示出来。

一、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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值