Javascript vue.js 使用计时器自动重新加载/刷新数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36572540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
vue.js auto reload / refresh data with timer
提问by Mike Thrussell
(New to Vue.js) I fetch data from a get request to display calendar information. I want this to update every 5 minutes.
(Vue.js 新手)我从 get 请求中获取数据以显示日历信息。我希望每 5 分钟更新一次。
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?
文档中没有关于自动重新加载的内容 - 我将如何实现这一点?我是否在文件中使用标准 javascript 或其他内容?
My complete app.js below:
我的完整 app.js 如下:
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',
});
回答by Linus Borg
No need to re-invent the wheel, window.setInterval()
does the job pretty well
无需重新发明轮子,window.setInterval()
做得很好
Vue.component('events', {
template: '#events-template',
data () {
return {
list: [],
timer: ''
}
},
created () {
this.fetchEventsList();
this.timer = setInterval(this.fetchEventsList, 300000)
},
methods: {
fetchEventsList () {
this.$http.get('events', (events) => {
this.list = events;
}).bind(this);
},
cancelAutoUpdate () { clearInterval(this.timer) }
},
beforeDestroy () {
clearInterval(this.timer)
}
});
new Vue({
el: 'body',
});