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

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

 

相关文章:

  • 2022-12-23
  • 2021-11-25
  • 2022-12-23
  • 2021-10-08
  • 2021-12-22
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-06
  • 2022-12-23
  • 2022-01-17
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案