Reputation: 11
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 class="time">
<time class="time__date">{{ data.date }}</time>
<time class="time__hour">{{ 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.
Upvotes: 1
Views: 836
Reputation: 799
@dystrykt9 Here is the working example. https://codesandbox.io/s/digital-clock-forked-32xmoh
The problem is today variable is constant (by constant i mean value not the const
). It is set once and in the setInterval
look the once set today variable each time there is same time(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.
Upvotes: 1