javascript - Vue每秒更新dom,简单时钟
问题描述
我正在尝试制作简单的时钟,我使用创建的项目@vue/cli
,目前有两个文件App.vue
,它们只是其他组件的主机/视图,clock.vue
内部导入App.vue
的组件和时钟组件代码如下。
<template>
<div class="container">
<div class="vertical">
{{ hours }}
<br />
{{ minutes }}
<br />
{{ seconds }}
<br />
{{ amPm }}
</div>
<div class="horizontal">
{{ hours }} : {{ minutes }} : {{ seconds }} : {{ amPm }}
</div>
</div>
</template>
<script lang="ts">
import Vue from "vue";
const date = new Date();
export default Vue.extend({
data() {
return {
hours: date.getHours(),
minutes: date.getMinutes(),
seconds: date.getSeconds(),
amPm: "AM",
interval: 0
};
},
mounted() {
this.interval = setInterval(this.updateClock, 1000);
},
beforeDestroy() {
clearInterval(this.interval);
},
methods: {
updateClock(): void {
this.hours = date.getHours();
this.minutes = date.getMinutes();
this.seconds = date.getSeconds();
this.amPm = this.hours >= 12 ? "PM" : "AM";
this.hours = this.hours % 12 || 12;
this.minutes = this.minutes < 10 ? 0 + this.minutes : this.minutes;
this.hours = this.hours < 10 ? 0 + this.hours : this.hours;
}
}
});
</script>
<style lang="scss">
.contaienr {
display: flex;
}
</style>
我希望时钟每秒更新一次,setInterval
但由于某种原因它仍然无法正常工作。检查了很多关于 stackoverflow 的答案,他们都使用setInterval
.
解决方案
您正在创建一个新日期并每秒引用一次(它永远不会改变) - 相反,在其中创建一个新引用updateClock
并删除另一个:
methods: {
updateClock(): void {
const date = new Date(); // create a new reference here
this.hours = date.getHours();
this.minutes = date.getMinutes();
this.seconds = date.getSeconds();
this.amPm = this.hours >= 12 ? "PM" : "AM";
this.hours = this.hours % 12 || 12;
this.minutes = this.minutes < 10 ? 0 + this.minutes : this.minutes;
this.hours = this.hours < 10 ? 0 + this.hours : this.hours;
}
}
推荐阅读
- python - 使用 Facebook Prophet 一次预测多个变量
- sql - 对数据进行分组并在 postgres 中每组显示 1 行
- azure - 无法在同一网络上访问 Cassandra
- c++ - 包含新指针的向量的 C++ 分配
- reactjs - 在 React 中使用包装器组件传递 props 可以吗?
- kendo-ui - 是否可以为网格重新排序调用不同的数据源更新方法?
- javascript - “对象”类型上不存在属性“过滤器”
- r - 嵌套 for 循环,在 R 中不同
- https - 如何在 Akamai 的根域和 www 域上设置 HTTPS?
- ldap - LDAP 中的组织单位和 posixGroup 有什么区别?