搜索

首页  >  问答  >  正文

在使用@pinia/nuxt时,将HTTP请求放在setInterval之外会在每次setInterval迭代时执行。

<p>我正在尝试使用@pinia/nuxt和nuxt 3构建一个计时器。当计时器启动时,我还想发起一个HTTP请求来同步我的数据库。</p><p>我面临的问题是,每次我调用start动作时,都会为setInterval循环的每次迭代发起一次HTTP请求,而我只想运行一次。</p><p>这是pinia模块。我是在组件的onClick事件中调用start动作。</p> <pre class="brush:php;toolbar:false;">state: () => ({ timer: { id: null, isRunning: false, time: 5, timer: 0, state: null, } as Timer, }), actions: { start() { this.timer.isRunning = true this.syncTimer() if (!this.timer.timer) { this.timer.timer = setInterval(() => { if (this.timer.time > 0) { this.timer.time-- } else { clearInterval(this.timer.timer) this.reset() } }, 1000) } }, stop() { this.timer.isRunning = false clearInterval(this.timer.timer) this.timer.timer = 0 }, reset() { this.stop() this.timer.time = 1500 }, syncTimer() { backendAPI<Timer>('/api/timer', { method: 'POST', body: this.timer }).then(({ error, data }) => { if (!error.value) { const id = data.value?.id ?? "" this.timer.id = id this.timer.state = "created" } }) } }</pre> <p>我的packages.json文件如下:</p> <pre class="brush:php;toolbar:false;">"devDependencies": { "@fortawesome/fontawesome-free": "^6.4.0", "@fullcalendar/core": "^6.1.8", "@fullcalendar/daygrid": "^6.1.8", "@fullcalendar/interaction": "^6.1.8", "@fullcalendar/timegrid": "^6.1.8", "@fullcalendar/vue3": "^6.1.8", "@iconify/vue": "^4.1.1", "@kevinmarrec/nuxt-pwa": "^0.17.0", "@mdi/font": "^7.2.96", "@nuxtjs/google-fonts": "^3.0.0", "@pinia-plugin-persistedstate/nuxt": "^1.1.1", "nuxt": "3.4.2", "sass": "^1.62.0", "vuetify": "^3.1.15" }, "dependencies": { "@pinia/nuxt": "^0.4.11", "pinia": "^2.1.3", "vite-plugin-vuetify": "^1.0.2" }</pre> <p><br /></p>
P粉413704245P粉413704245487 天前581

全部回复(1)我来回复

  • P粉976737101

    P粉9767371012023-07-29 10:03:44

    正如我在评论中提到的,实现实时功能的正确方式是使用sockets。但是,如果你需要以轮询的方式进行操作,你可以编写一个守卫,类似于以下示例:

    actions: {
      start() {
        if (this.timer.isRunning) return;
    
        this.timer.isRunning = true;
        this.syncTimer();
    
        this.timer.timer = setInterval(() => {
          if (this.timer.time > 0) {
            this.timer.time--;
          } else {
            clearInterval(this.timer.timer);
            this.reset();
          }
        }, 1000);
      },
      // ...
    }

    希望有用

    回复
    0
  • 取消回复