【问题标题】:Slow down the rate of requests in Vue.js updated method in Django web application减慢 Django Web 应用程序中 Vue.js 更新方法中的请求速率
【发布时间】:2018-12-08 11:35:43
【问题描述】:

我在 Django 模板中有一个 Vue.js 视图。 Vue 从 Django Rest Framework 端点提取数据以显示在视图中。我的代码如下:

    const app = new Vue({
        el: '#app',
        delimiters: ["[%", "%]"],
        data: {
            dedicated_server: [],
        },
        created() {
            fetch('/api/dedicated-server/{{ object.id }}/')
                .then(response => response.json())
                .then(json => {
                    this.dedicated_server = json;
                })
        },
        updated() {
            /* TODO: Try and limit the number of requests to the API */
            fetch('/api/dedicated-server/{{ object.id }}/')
                .then(response => response.json())
                .then(json => {
                    this.dedicated_server = json
                })
        },
    });

如您所见,我有一个更新的方法,它轮询 Restful 端点以在数据更改时更新页面。这一切都很好,但它似乎每秒轮询 3 到 5 次 Restful API 端点。这在开发中很好,但如果我有 100 人访问此页面,那么它将通过请求杀死我的服务器。

有没有办法限制 Vue.js 检查数据是否已更新的次数?如果你能说每 5 秒检查一次,那就太好了。

【问题讨论】:

    标签: javascript python django vue.js vuejs2


    【解决方案1】:

    您可以使用setInterval 每 5 秒运行一次。设置在created,不用担心updated

        setInterval(() => 
            fetch('/api/dedicated-server/{{ object.id }}/')
                .then(response => response.json())
                .then(json => {
                    this.dedicated_server = json;
                }),
            5000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多