vue获取动态时间戳

1.html中

    <div class="dev_time">{{ nowDate }}</div>

2.data中定义

    data() {
      return {
        nowDate: ''
      }
    }

3.在methods中定义转化时间戳的函数并添加定时器

    // 获取时间
    currentTime () {
      setInterval(this.formatDate, 500)
    },
    formatDate () {
      let time = new Date()
      let year = time.getFullYear()
      const month = (time.getMonth() + 1).toString().padStart(2,'0')
      const  date = (time.getDate()).toString().padStart(2,'0')
      const hours = (time.getHours()).toString().padStart(2,'0')
      const minute = (time.getMinutes()).toString().padStart(2,'0')
      const second = (time.getSeconds()).toString().padStart(2,'0')
      this.nowDate = year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
    }

4.在生命周期函数mounted中执行定时器函数

    mounted () {
      this.currentTime()
    }

5.在生命周期函数beforeDestroy函数中清除定时器

    beforeDestroy () {
      if (this.formatDate) {
        clearInterval(this.formatDate) // 在Vue实例销毁前,清除时间定时器
      }
    }

本文只作为个人学习记录......

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容