Make computed Vue properties dependent on current time? Make computed Vue properties dependent on current time? vue.js vue.js

Make computed Vue properties dependent on current time?


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.


One possibility for your case is $forceUpdate(). However, it should be note that it will work specifically for your case because you're NOT using child components.

If you were to use child components, you would then need to use slots within the parent component and insert the children within their respective slots.

So, for example, you could do:

created() {    setInterval(() => {        this.$forceUpdate()    }, 5000)}

Which will cause the entire component to re-render. This may or may not be the desirable interaction you're looking for.


You could create a time variable that you update every second then use this variable in your computed properties.

new Vue({  el: "#app",  data: {    time: ''  },  computed: {    computedValue: function(){        return this.time;    }  },  mounted: function(){    var app = this;    setInterval(function(){      app.time = parseInt(new Date().getTime() / 1000);        }, 1000);  }})

https://jsfiddle.net/ecwnvudz/