美文网首页
vue 获取当前时间,定时刷新

vue 获取当前时间,定时刷新

作者: 咸鱼不闲吧 | 来源:发表于2020-03-13 13:49 被阅读0次

vue 定时刷新 当前时间

<div>{{ currDate }}</div>
data() {
  return {
    timer: '',
    currDate: new Date()
  } 
},
created() {
  const appendZero = (obj) => {
    if (obj < 10) {
      return '0' + obj
    } else {
      return obj
    }
  }
  const getCurrTime = () => {
    this.currDate = 
      new Date().getFullYear() + '年' +
      appendZero(new Date().getMonth() + 1) + '月' + 
      appendZero(new Date().getDate()) + '日'  + 
      appendZero(new Date().getHours()) + ' : ' + 
      appendZero(new Date().getMinutes()) + ': ' + 
      appendZero(new Date().getSeconds())
  }
  getCurrTime();
  this.timer = setInterval(() => {
    getCurrTime();
  }, 1000);
},
beforeDestroy() {
  if(this.timer) {
    clearInterval(this.timer)
  }
}

最终效果

image.png

相关文章

网友评论

      本文标题:vue 获取当前时间,定时刷新

      本文链接:https://www.haomeiwen.com/subject/cbthshtx.html