Heim  >  Fragen und Antworten  >  Hauptteil

Bei Verwendung von @pinia/nuxt werden HTTP-Anfragen, die innerhalb einer setInterval-Schleife ausgeführt werden, bei jeder setInterval-Iteration ausgeführt.

<p>Ich versuche, einen Timer mit @pinia/nuxt und nuxt 3 zu erstellen. Wenn der Timer startet, möchte ich auch eine HTTP-Anfrage initiieren, um meine Datenbank zu synchronisieren. </p><p>Das Problem, mit dem ich konfrontiert bin, besteht darin, dass die HTTP-Anfrage jedes Mal, wenn ich die Startaktion aufrufe, bei jeder Iteration der setInterval-Schleife ausgeführt wird, während ich möchte, dass sie nur einmal ausgeführt wird. </p><p>Das Folgende ist mein Pinia-Modul. Ich rufe die Startaktion über das onClick-Ereignis in der Komponente auf. </p><p><code></code><code></code></p> <pre class="brush:php;toolbar:false;">state: () => Timer: { ID: null, isRunning: false, Zeit: 5, Timer: 0, Zustand: null, } als Timer, }), Aktionen: { Start() { this.timer.isRunning = true this.syncTimer() if (!this.timer.timer) { this.timer.timer = setInterval(() => { if (this.timer.time > 0) { this.timer.time-- } anders { clearInterval(this.timer.timer) this.reset() } }, 1000) } }, stoppen() { this.timer.isRunning = false clearInterval(this.timer.timer) this.timer.timer = 0 }, zurücksetzen() { this.stop() this.timer.time = 1500 }, syncTimer() { backendAPI<Timer>('/api/timer', { Methode: 'POST', Körper: this.timer }).then(({ Fehler, Daten }) => { if (!error.value) { const id = data.value?.id ?? this.timer.id = id this.timer.state = "erstellt" } }) } }</pre> <p>Meine Datei packets.json lautet wie folgt:</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“ }, "Abhängigkeiten": { „@pinia/nuxt“: „^0.4.11“, "pinia": "^2.1.3", „vite-plugin-vuetify“: „^1.0.2“ }</pre> <p><br /></p>
P粉596191963P粉596191963449 Tage vor499

Antworte allen(1)Ich werde antworten

  • P粉384679266

    P粉3846792662023-07-28 11:53:00

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

    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);
      },
      // ...
    }

    应该可以

    Antwort
    0
  • StornierenAntwort