当前时间不足10补0(VUE/JS)

<template>
    <div id="zptime">
        {{setDate}}
    </div>
</template>

<script>
  export default {
    name: 'zptime',
    data() {
      return {
        date: new Date(),
      }
    },
    computed: {
      setDate() {
        let year = this.timeAdd0(this.date.getFullYear().toString()),
          month = this.timeAdd0((this.date.getMonth() + 1).toString()),
          date = this.timeAdd0(this.date.getDate().toString()),
          hour = this.timeAdd0(this.date.getHours().toString()),
          minute = this.timeAdd0(this.date.getMinutes().toString()),
          sec = this.timeAdd0(this.date.getSeconds().toString());
        // return `当前时间: ${this.date.getFullYear()}.${this.date.getMonth() + 1}.${this.date.getDate()} ${this.date.getHours()}:${this.date.getMinutes()}:${this.date.getSeconds()}`
        return `当前时间: ${year}.${month}.${date} ${hour}:${minute}:${sec}`
      }
    },
    mounted() {
      setInterval(() => {
        this.date = new Date()
      }, 1000);
    },
    methods: {
      timeAdd0(m) {
        if (m.length < 2) {
          m = '0' + m;
        }
        return m
      }
    }

  }
</script>
<style scoped>
    #zptime {
        line-height: 75px;
        color: rgba(255, 255, 255, 0.6);
        font-size: 20px;
    }
</style>
原文地址:https://www.cnblogs.com/cherylgi/p/13889447.html