gpt4 book ai didi

javascript - Vue 每秒更新 dom,简单时钟

转载 作者:行者123 更新时间:2023-12-01 00:09:44 30 4
gpt4 key购买 nike

我正在尝试制作简单的时钟,我使用 @vue/cli 创建了该项目,目前有两个文件 App.vue 这只是一个主机/ View 其他组件,以及App.vue内部导入的clock.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;
}
}

关于javascript - Vue 每秒更新 dom,简单时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60153611/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com