I am learning Vue.JS and for my first project I am trying to make a digital clock using Composition API, the problem I ran into is, that it seems the function won't add time for my clock.
Here is my code:
<template>
<div >
<div >
<span>{{time}}</span>
</div>
</div>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
name: 'App',
setup(){
let clock = ref(new Date())
let time = clock.value.toLocaleTimeString('lv-LV')
const showLocalTime = function(){
setInterval(
time,1000)
};
onMounted(() => {
showLocalTime()
})
return{
time
}
}
}
</script>
I have also tried replacing onMounted
with onBeforeMount
but that didn't help either, could you help me understand why it isn't working?
CodePudding user response:
You need to update time :
const { ref, onBeforeUnmount } = Vue
const app = Vue.createApp({
setup(){
const time = ref((new Date()).toLocaleTimeString('lv-LV'))
const updateCurrentTime = () => {
time.value = (new Date()).toLocaleTimeString('lv-LV')
}
const updateTimeInterval = setInterval(updateCurrentTime, 1000)
onBeforeUnmount(() => clearInterval(updateTimeInterval))
return { time }
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div >
<div >
<span>{{ time }}</span>
</div>
</div>
</div>
CodePudding user response:
There is no need for clock
to be a ref since this value is not changing in the template. On the other hand time
should be a ref since this is being updated every second.
On the interval you should update with the current Date. For that you need to call new Date()
again in order to get the actual date otherwise you are getting the date from a second ago and updating the time with that old date.
The onMounted
hook is not needed since you're changing only a variable.
Your setup()
could look like this:
setup() {
let now = new Date();
const time = ref(now.toLocaleTimeString("lv-LV"));
setInterval(() => {
now = new Date();
time.value = now.toLocaleTimeString("lv-LV");
}, 1000);
return {
time,
};
},
Here a working example to play around