vue時計機能:リアルタイム時間を動的に表示(時間フォーマットプラグインdayjs)

8193 ワード

  • 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>