How to set a timer using the Vue.js class

im, just using Vue.js to update posts on the im messing around site, this is what ive got so far (I'm still learning javascript and not too big in it)

[app.js]

var Vue = require('vue'); Vue.use(require('vue-resource')); var app = new Vue({ el: '#app', components: { 'postlist' : require('./components/postlist/postlist.js') } }); 

[postlist.js]

 module.exports = { template: require('./postlist.template.html'), data: function () { return { 'search': '', 'posts' : {} } }, methods: { 'updatePosts' : function() { this.$http.get('api/posts', function(responce, status, request) { this.$set('posts', responce.data); }); } } }; 

What I'm looking for is for updatePosts to fire every x seconds, how do I do this?

ive tried to do this in app.js

 setInterval(function() { app.components.postlist.methods.updatePosts(); // doesnt work app.postlist.updatePosts(); //doesnt work either }, 500); 

and tried to put setInterval in the component itself

im pretty lost with this, what is the best way to achieve this?

does updatePosts work every x seconds?

+8
javascript jquery
source share
2 answers

I also have problems with areas in Vue.

it should work

 module.exports = { template: require('./postlist.template.html'), data: function () { return { 'search': '', posts: {} } }, methods: { updatePosts: function () { var self = this; self.$http.get('api/posts', function(responce, status, request) { self.posts = responce.data; setTimeout(function(){ self.updatePosts() }, 2000); }); } }, created: function () { this.updatePosts(); } } 

Functions in Vue work differently because your updatePosts method updatePosts not a regular function. This function is defined in the $vm.methods object. therefore, it cannot be called regularly, like setTimeout($vm.updatePosts) . Actually $vm.updatePosts does not exist. if you named it as $vm.updatePosts() , this is a completely different story. $vm instance automatically calls its method ... So the correct way is setTimeout(function(){ self.updatePosts() },2000)

+5
source share

You can start the request loop in created or somewhere else on the lifecycle. It is also probably best to use recursion here so you can wait for an answer to return before sending another. I have not tested this code completely, but it should work.

 module.exports = { template: require('./postlist.template.html'), data: function () { return { 'search': '', posts: {} } }, methods: { updatePosts: function () { this.$http.get('api/posts', function(responce, status, request) { this.posts = responce.data; setTimeout(this.updatePosts, 2000); }); } }, created: function () { this.updatePosts(); } } 
+2
source share

All Articles