vue.js使用计时器自动重新加载/刷新数据

Mik*_*ell 28 javascript reload vue.js

(Vue.js新手)我从get请求中获取数据以显示日历信息.我希望每5分钟更新一次.

关于自动重装的文档中没有任何内容 - 我将如何实现这一点?我是否在文件或其他内容中使用标准JavaScript?

我的完整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',


});
Run Code Online (Sandbox Code Playgroud)

Lin*_*org 98

无需重新发明轮子,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',
});
Run Code Online (Sandbox Code Playgroud)

  • 建议:当组件被"销毁()"时运行`cancelAutoUpdate()` (9认同)
  • 完善!添加取消功能的好工作.谢谢. (2认同)
  • 做得好Linus Borg。简要说明一下,`clearIntervall(this.timer)`中有一个错字。应该是`clearInterval(this.timer)`。谢谢! (2认同)