在使用@pinia/nuxt時,將HTTP請求放在setInterval之外會在每次setInterval迭代時執行。
P粉413704245
P粉413704245 2023-07-28 14:34:18
0
1
391
<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粉413704245
P粉413704245

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!