vue获取当前时间 实时刷新

需求:获取当前系统时间,在页面上展示 年月日 时分秒 ,并且实时刷新,和系统时间保持一致

第一步:在deta 里面声明两个变量
第二步:把时间调用写在created() 生命周期里面,进入页面就需要调用
第三步:离开页面使用beforeDestroy() 销毁
如下:
data() {
    return {
      timer: "",//定义一个定时器的变量
      currentTime: new Date(), // 获取当前时间
    };
  },
created() {
    var _this = this; //声明一个变量指向Vue实例this,保证作用域一致
    this.timer = setInterval(function() {
      _this.currentTime = //修改数据date
        new Date().getFullYear() +
        "-" +
        (new Date().getMonth() + 1) +
        "-" +
        new Date().getDate() +
        " " +
        new Date().getHours() +
        ":" +
        new Date().getMinutes() +
        ": " +
        new Date().getSeconds();
    }, 1000);
  },
beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前,清除我们的定时器
    }
  }

这样就能满足需求了  拿到的时间格式是 2019-8-16 8:9: 5  

小于10的没有加  0 

如果需要的话可以使用下面的方法加上就可以了

//过滤加0
appendZero(obj) {
if (obj < 10) {
return "0" + obj;
} else {
return obj;
}
},

猜你喜欢

转载自www.cnblogs.com/lidonglin/p/11362384.html