WEB笔记实时显示时间

4次阅读

共计 861 个字符,预计需要花费 3 分钟才能阅读完成。

以 VUE 框架为例子,实现显示实时的时间

首先在 data 中声明一个变量

data() {
  return {date: new Date(),
  };
},
<div id="app">
    {{date}}
</div>
<script>
export default {data() {
    return {date: new Date()
    };
  },
  mounted() {
    let _this = this; // 声明一个变量指向 Vue 实例 this,保证作用域一致
    this.timer = setInterval(() => {_this.date = new Date(); // 修改数据 date
    }, 1000)
  },
  beforeDestroy() {if (this.timer) {clearInterval(this.timer); // 在 Vue 实例销毁前,清除我们的定时器
    }
  }
};
</script>

这样子获得的时间是浏览器默认的时间格式
可以对时间进行格式化,按需求显示所需要的时间样式
例如:
增加一个 showtime 方法,使其只显示时分

    showtime(time) {var date = new Date(time);
      var year = date.getFullYear();
      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 `${hours}:${minutes}`;
    },

正文完
 0