Mike Thrussell Mike Thrussell - 7 months ago 367
Javascript Question

vue.js auto reload / refresh data with timer

(New to Vue.js) I fetch data from a get request to display calendar information. I want this to update every 5 minutes.

Nothing in the docs about auto reload - how would I go about implementing this? Do I use standard javascript within the file or something else?

My complete app.js below:

Vue.component('events', {
template: '#events-template',

data: function() {
return {
list: []
}
},

created: function() {

this.fetchEventsList();
},

methods: {

fetchEventsList: function() {

this.$http.get('events', function(events) {

this.list = events;

}).bind(this);

}

}

});

new Vue({
el: 'body',


});

Answer

No need to re-invent the wheel, window.setInterval() does the job pretty well:

data: function() {
    return {
        list: [],
        timer: ''
    }
},
created: function() {

    this.fetchEventsList();
    this.timer = setInterval(this.fetchEventsList, 300000)

},
methods: {

    fetchEventsList: function() {

        this.$http.get('events', function(events) {

            this.list = events;

        }).bind(this);

    },
    cancelAutoUpdate: function() { clearInterval(this.timer) }

},
beforeDestroy() {
  clearIntervall(this.timer)
}
Comments