LocalTime.vue 2.49 KB
<template>
  <div :style="{ textAlign: config.text.textAlign }">
    <span class="text" :style="getStyle()">
      <template v-if="config.showYear">{{ dateYear }}</template>
      <template v-if="config.showWeek">{{ dateWeek }}</template>
      <template v-if="config.showDay">{{ dateDay }}</template>
    </span>
  </div>
</template>
<script>
  export default {
    name: 'LocalTime',
    props: {
      config: {
        type: Object,
        default: null,
      },
    },
    data() {
      return {
        dateDay: null,
        dateYear: null,
        dateWeek: null,
        weekday: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      }
    },
    mounted() {
      this.refreshTime()
    },
    methods: {
      formatTime(time, fmt) {
        if (!time) return ''
        else {
          const date = new Date(time)
          const o = {
            'M+': date.getMonth() + 1,
            'd+': date.getDate(),
            'H+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds(),
            'q+': Math.floor((date.getMonth() + 3) / 3),
            S: date.getMilliseconds(),
          }
          if (/(y+)/.test(fmt))
            fmt = fmt.replace(
              RegExp.$1,
              (date.getFullYear() + '').substr(4 - RegExp.$1.length)
            )
          for (const k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
              fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length === 1
                  ? o[k]
                  : ('00' + o[k]).substr(('' + o[k]).length)
              )
            }
          }
          return fmt
        }
      },
      refreshTime() {
        setInterval(() => {
          this.dateDay = this.formatTime(
            new Date(),
            this.config.formatDay ? this.config.formatDay : 'HH: mm: ss'
          )
          this.dateYear = this.formatTime(
            new Date(),
            this.config.formatYear ? this.config.formatYear : 'yyyy-MM-dd'
          )
          this.dateWeek = this.weekday[new Date().getDay()]
        }, 1000)
      },
      getStyle() {
        if (this.config.isDiyStyle && this.config.diyStyle) {
          return JSON.parse(this.config.diyStyle)
        } else {
          return {
            fontSize: this.config.text.fontSize,
            color: this.config.text.color,
            fontWeight: this.config.text.fontWeight,
          }
        }
      },
    },
  }
</script>
<style>
  .text {
    display: inline-block;
  }
</style>