vue实时显示当前时间

代码: 

  export default{
    data(){
      return{
        date:new Date()
      }
    },
    methods:{
      dateFormat(time) {
          var date=new Date(time);
          var year=date.getFullYear();
          /* 在日期格式中,月份是从0开始的,因此要加0
          * 使用三元表达式在小于10的前面加0,以达到格式统一  如 09:11:05
          * */
          var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
          var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
          var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
          var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
          var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
          // 拼接
          return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
      }
    },
    mounted() {
          //显示当前日期时间
          let _this = this// 声明一个变量指向Vue实例this,保证作用域一致
          this.timer = setInterval(() => {
           _this.date = new Date(); // 修改数据date
           }, 1000)
       },
      beforeDestroy() {
       if (this.timer) {
        clearInterval(this.timer); // 在Vue实例销毁前,清除我们的定时器
      }
}

使用:

   <div>{{dateFormat(date)}}</div>

效果图:

发布了319 篇原创文章 · 获赞 124 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_40323256/article/details/102867033