Search code examples
vue.jstimecomputed-properties

Make computed Vue properties dependent on current time?


I have a collection of Events. These will render in lists according to their status - upcoming/live/previous. Thus the rendering is dependent on the current time. How can I make the computed properties to update/recompute as time goes by?

<template>
    <div>
        <h2>Upcoming events</h2>
        <p v-bind:key="event.name" v-for="event in upcomingEvents">{{ event.name }}</p>

        <h2>Live events</h2>
        <p v-bind:key="event.name" v-for="event in liveEvents">{{ event.name }}</p>

        <h2>Previous events</h2>
        <p v-bind:key="event.name" v-for="event in previousEvents">{{ event.name }}</p>
    </div>
</template>

<script>
    import Event from '../Event.js'

    export default {
        data() {
            return {
                events: []
            }
        },

        computed: {
            upcomingEvents() {
                return this.events.filter(event => event.isUpcoming())
            },

            liveEvents() {
                return this.events.filter(event => event.isLive())
            },

            previousEvents() {
                return this.events.filter(event => event.isPrevious())
            },
        },

        mounted() {
            // this.events are populated here 
        }
    }
</script>

Solution

  • You can declare a time-dependent data variable and use setInterval() to update it:

    data() {
        return {
            events: [],
            now: Date.now()
        }
    },
    created() {
        var self = this
        setInterval(function () {
             self.now = Date.now()
        }, 1000)
    },
    computed: {
        upcomingEvents() {
            return this.events.filter(event => event.isUpcoming(this.now))
        },
        liveEvents() {
            return this.events.filter(event => event.isLive(this.now))
        },
        previousEvents() {
            return this.events.filter(event => event.isPrevious(this.now))
        }
    }
    

    Note that you need to use now in computed properties to make them update.