To make a computed property in Vue.js dependent on the current time, you can utilize a combination of JavaScript’s Date
object and Vue’s reactivity system.
For example, we write
<template>
<div>
<p>The current time is: {{ currentTime }}</p>
<p>The current hour is: {{ currentHour }}</p>
</div>
</template>
<script>
export default {
data() {
return {
currentTime: new Date()
};
},
computed: {
currentHour() {
return this.currentTime.getHours();
}
},
created() {
// Update the currentTime property every second
setInterval(() => {
this.currentTime = new Date();
}, 1000);
}
};
</script>
In this example, we have a computed property currentHour
that depends on the currentTime
data property.
We initialize currentTime
with the current date and time.
We update currentTime
every second using setInterval
to ensure that the computed property is re-evaluated as time progresses.
With this setup, currentHour
will automatically update every second to reflect the current hour based on the system time.
We can similarly create computed properties dependent on other time-related aspects such as minutes, seconds, etc., by accessing different methods of the Date
object.