vue.js:在哪里放置定期重复的后台查询

sai*_*tam 6 javascript background-process vue.js

我想每 15 秒查询一次 API 服务,这样我就可以从数据库获取数据并检查某些内容是否发生更改。如果有变化,那么我的前端会根据 vue 的工作原理自动更新。

while (true) {
    setTimeout(function() { 
        QueryService.orders().then(response => 
            this.orders = response.data
        )
    }, 15000)
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 这是解决此类问题的好方法吗?
  2. 代码中放置此类循环的最佳位置是什么?

编辑:

使用setInterval()似乎是正确的方法,但是setInterval在created()挂钩中使用轮询函数根本不会影响数据表。它显示“没有可用数据”:

data () {
    return {
        headers [
            { ... },
            { ... }
        ],
        orders: []
}

created () {
    setInterval(function() { 
        QueryService.orders().then(response => this.orders = response.data)
    }, 15000)
}
Run Code Online (Sandbox Code Playgroud)

使用轮询功能无需setInterval工作,并像往常一样用数据填充我的数据表:

created () {
    QueryService.orders().then(response => this.orders = response.data)
}
Run Code Online (Sandbox Code Playgroud)

Len*_*eph 1

像这样的循环将进入mounted ()生命周期挂钩内的组件脚本中。

这意味着一旦组件加载,您的循环就会触发。有关此技术的详细指导,Vue 文档以及本文是一个很好的第一

  • 我认为您需要将 while 循环转换为 setInterval 函数。由于 while 循环,事件循环被永远阻塞,因为您的循环始终为真。如果您在函数上使用 setInterval,它将每 15 秒运行一次数据调用,然后再次释放事件循环。 (3认同)
  • 我现在看到了这个问题。如果你看一下 W00ngy 的代码,你会看到他实例化了一个名为“polling”的数据字段。这允许他创建一个方法函数,通过“this.polling”将数据变量设置为设置间隔函数,该函数检索数据。因此,为了使您的表具有反应性,它可能需要来自数据属性的这种模式。尝试模仿 W00ngy 的例子。 (2认同)