所以我正在做一個 vue.js 專案,我試圖讓時間每秒更新一次。我已經在 data() 中初始化了時間,然后創建了一個應該更新它的函式,然后在 mount() 中呼叫該函式以每秒重繪 一次。問題是當我呼叫 updateTime() 時,它一直告訴我“現在”沒有定義。這是為什么?
<script>
import { createDOMCompilerError } from "@vue/compiler-dom";
export default {
data() {
const now = new Date();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();
return {
now,
hours,
minutes,
seconds,
};
},
methods: {
updateTime() {
this.now = new Date();
this.hours = now.getHours();
this.minutes = now.getMinutes();
this.seconds = now.getSeconds();
},
},
mounted() {
setInterval(() => {
this.updateTime();
}, 1000);
},
unmounted() {
clearInterval();
},
};
</script>
uj5u.com熱心網友回復:
this.now
分配給this.hours
等時需要使用
this.now = new Date();
this.hours = this.now.getHours();
this.minutes = this.now.getMinutes();
this.seconds = this.now.getSeconds();
另外注意clearInterval
需要傳入一個區間ID,運行時會回傳setInterval
https://developer.mozilla.org/en-US/docs/Web/API/clearInterval
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/506191.html
下一篇:如何拆分字串并僅回傳剩余值?