Im creating a simple vue.js clock, thats why im really confused why it doesn't work. I tried to implement multiple solutions i found online, but every one of them failed to solve this problem.
App was initialized with npm init vue@latest
. Im using the composition API.
Here's my js:
import {
reactive,
computed,
onMounted,
onBeforeUnmount
} from 'vue';
const data = reactive({
date: '',
time: ''
});
const today = new Date();
const getCurrentTime = () => {
const hours = today.getHours();
const minutes = today.getMinutes();
const seconds = today.getSeconds();
const zeroPadding = (num) => {
if (num < 10) {
return `0${num}`
} else {
return num;
}
};
data.time = `${zeroPadding(hours)}:${zeroPadding(minutes)}:${zeroPadding(seconds)}`;
}
onMounted(() => {
setInterval(getCurrentTime, 1000);
});
And here's the html:
<div >
<time >{{ data.date }}</time>
<time >{{ data.time}}</time>
</div>
I even copied this solution https://dev.to/snehalkadwe/digital-clock-using-vue-3-composition-api-5cmc, but it also isn't updating the clock. I've had enough, this is my first post on stackoverflow, so yeah, it's a big deal.
CodePudding user response:
@user20717282 Although I didn't reproduce your issue, it would have been great if you could provide a sandbox link, but till then you can try the following variations:
- I think you should call
setInterval(getCurrentTime, 1000);
outside ,onMounted()
function. ProbablyonMounted
is clearing it's context/scope once it's completed. So wrap the setInterval inside a function and call that function fromonMounted()
. - or try to change code to
setInterval(()=>{ getCurrentTime() }, 1000);
- Add a console.log in
getCurrentTime
function to check even if it's being called or not.
Please update me once you have tried these!
CodePudding user response:
@dystrykt9 Here is the working example. https://codesandbox.io/s/digital-clock-forked-32xmoh
The problem is today variable is constant. It is set once and in the setInterval
you look the same value each time and get hour, minute and second. The reactive data.time
value is same each time. But what we need is the today variable needs to get updated with latest time i.e. hour, minute and second.
I also do not get the point of data.date
. May be you can use ref or single property or may be you are using that for different logic but is not present in the question code snippet.
The solution would be put the total variable in the setInterval so that every time the variable is set to latest time (hour, minute and second).
For better knowing the problem I have console.log in setInterval
callback function. You can check by with setting today outside the callback and inside the callback.