我只是使用 Vue.js 来更新我正在搞乱的网站上的帖子,这就是我到目前为止所得到的(我仍在学习 javascript,并且不太擅长)
[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);
});
}
}
};
我正在寻找的是让 updatePosts 每 x 秒触发一次,我该怎么做?
我试过在 app.js
中这样做setInterval(function()
{
app.components.postlist.methods.updatePosts(); // doesnt work
app.postlist.updatePosts(); //doesnt work either
}, 500);
并尝试将 setInterval 放入组件本身
我对此很迷茫,实现这一目标的最佳方法是什么?
updatePosts 每 x 秒运行一次?
最佳答案
我也遇到了 Vue 中范围的问题。
这应该可行
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();
}
}
Vue 中的函数的工作方式有点不同,因为您的方法 updatePosts
不是常规函数。它是在 $vm.methods
对象中定义的函数。所以不能像setTimeout($vm.updatePosts)
那样定期调用。实际上 $vm.updatePosts
并不存在。如果你像 $vm.updatePosts()
这样调用它,那就是另一回事了。 $vm
实例自动调用它的方法...所以正确的方法是 setTimeout(function(){ self.updatePosts() },2000)
关于javascript - 如何使用 Vue.js 类设置计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33065828/