【发布时间】:2020-05-25 23:03:44
【问题描述】:
我正在尝试制作简单的时钟,我使用@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。
【问题讨论】:
-
您的
style标签中有错字 - 应该是.container而不是.contaienr
标签: javascript typescript vuejs2 vue-component