vue定时器实现实时时间

data() {
    
    
  return {
    
    
     timer: "",
     dateTime: this.getCurrentTime(),//当前时间
  }
},
created() {
    
    
   //定时器:当前时间
   this.timer = setInterval(() => {
    
    
      this.dateTime = this.getCurrentTime();
   }, 1000);
},
methods: {
    
    
   //获取当前时间
   getCurrentTime() {
    
    
      return this.$moment(new Date()).format('YYYY/MM/DD HH:mm:ss');
   }
},
beforeDestroy() {
    
    
   //在vue实例销毁前,清除定时器
   if (this.timer) {
    
    
      clearInterval(this.timer);
   }
},

上文中的$moment为整理时间格式的插件。

引用moment插件

npm i moment --save

//main.js
import moment from 'moment'
Vue.prototype.$moment = moment;

猜你喜欢

转载自blog.csdn.net/qweqwe2277/article/details/87938323