vue 钟表功能:动态显示实时时间(时间格式化插件dayjs)

  • npm安装
npm install dayjs --save
  • main.js
import dayjs from "dayjs"
Vue.prototype.dayjs = dayjs; //可以全局使用dayjs
  • 实例
/* 时间格式化 */
this.dayjs().format('YYYY-MM-DD')  // 当前日期:年月日
this.dayjs().format("YYYY-MM-DD HH:mm:ss")  // 当前日期:年月日 时分秒

/* 获取过去七天时间 */
 for (let i = 6; i >= 0; i--) {
    
    
   let date = this.dayjs(this.dayjs()-24*60*60*1000*i).format("YYYY-MM-DD")
   console.log(date)
 }

dayjs实现钟表功能:动态显示实时时间

<template>
  <div id="app">
    {
    
    {
    
    this.datetime}}
  </div>
</template>

<script>
  export default {
    
    
    name: "app",
    data() {
    
    
      return {
    
    
        timer: '',
        datetime: ''
      }
    },
    mounted() {
    
    
      /* 每秒定时刷新 */
      this.timer = setInterval(() => {
    
    
        this.datetime = this.dayjs().format("YYYY-MM-DD HH:mm:ss")
        console.log(this.datetime)
      }, 1000)
    },
    beforeDestroy() {
    
    
      /* 离开页面前销毁定时器 */
      if(this.timer){
    
    
        clearInterval(this.timer);
      }
    }
  };
</script>

<style lang="less" scoped>

</style>

猜你喜欢

转载自blog.csdn.net/weixin_42201180/article/details/107832001