Vue页面上实时显示当前时间,每秒更新

有时候我们需要在页面上添加一个类似时钟的东西来实时显示当前时间,这个时候我们可以利用定时器来完成这个功能

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

 

posted @ 2020-09-13 21:26  haha-uu  阅读(2026)  评论(0编辑  收藏  举报