vue获取当前时间并实时刷新

344 阅读1分钟

年月日时分秒都有,根据自己的需求改

Snipaste_2022-01-11_11-58-38.png

<!--
 * @Author: liuyq
 * @Date: 2021-12-12 19:53:47
 * @LastEditTime: 2022-01-07 14:38:19
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \zichandaping\src\view\fHeader\fHeader.vue
-->
<template>
  <div class="fHeader">
    <div class="title">标题</div>
    <div class="time">
      <img class="y1" src="https://yashi-daping.oss-cn-hangzhou.aliyuncs.com/jingjifazhan/fimg1.png" />
      <span class="y2">{{ nowDate }}</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      nowDate: "", // 当前日期
    };
  },
  methods: {
    currentTime() {
      setInterval(this.formatDate, 500);
    },
    formatDate() {
      let date = new Date();
      let year = date.getFullYear(); // 年
      let month = date.getMonth() + 1; // 月
      let day = date.getDate(); // 日
      let week = date.getDay(); // 星期
      let weekArr = [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" ];
      let hour = date.getHours(); // 时
      hour = hour < 10 ? "0" + hour : hour; // 如果只有一位,则前面补零
      let minute = date.getMinutes(); // 分
      minute = minute < 10 ? "0" + minute : minute; // 如果只有一位,则前面补零
      let second = date.getSeconds(); // 秒
      second = second < 10 ? "0" + second : second; // 如果只有一位,则前面补零
      this.nowDate = `${hour}:${minute}:${second} ${weekArr[week]}`;
      //this.nowDate = `${year}/${month}/${day} ${hour}:${minute}:${second} ${weekArr[week]}`;
    }
  },
  mounted() {
    this.currentTime();
  },
  // 销毁定时器
  beforeDestroy() {
    if (this.formatDate) {
      clearInterval(this.formatDate); // 在Vue实例销毁前,清除时间定时器
    }
  }
};
</script>

<style lang="scss" scoped>
.fHeader {
  width: 100%;
  height: 83rem;
  background-image: url("https://yashi-daping.oss-cn-hangzhou.aliyuncs.com/zhihuishewu/head.png");
  background-repeat: no-repeat;
  background-position: bottom center;
  background-size: 100% 100%;
  position: relative;
  .title {
    height: 60rem;
    font-size: 38rem;
    font-family: PingFang;
    font-weight: bold;
    // letter-spacing: 4rem;
    color: #ffffff;
    line-height: 60rem;
    text-shadow: 0px 0px 10px rgba(51, 173, 255, 0.4);
    background: linear-gradient(180deg, #ffffff 0%, #bdd1ff 100%);
    background-clip: text;
    -webkit-text-fill-color: transparent;
    text-align: center;
  }
  .time {
    position: absolute;
    right: 40rem;
    top: 14rem;
    display: flex;
    align-items: center;
    .y1 {
      width: 20rem;
      height: 20rem;
      margin-right: 10rem;
    }
    .y2 {
      font-size: 24rem;
      font-weight: bold;
      color: #2CB3F0;
      margin-right: 15rem;
    }
    .y3 {
      font-size: 24rem;
      font-weight: bold;
      color: #fff;
    }
  }
}
</style>