首页 > 解决方案 > 如何在 vuex 状态上设置间隔并从模板中清除它?

问题描述

我试图通过在挂载时启动 setInterval 函数并在销毁时启动 clearInterval 来跟踪 Nuxt 中的页面访问时间。但是我需要将函数设置为 vuex 状态。我的方法如下:

//_index.vue
mounted() 
{
   this.$store.dispatch('business/initiate_timer');
},    

destroyed() {
   this.$store.dispatch('business/clear_timer');
      
   var timerPayload = {}
   timerPayload.time = this.$store.state.business.timer / 60;
   this.$store.dispatch('business/action_to_post_request_with_timer', timerPayload)
 }

这是我的模块化商店中与计时器相关的任务:business.js

//business.js

export const state = () => ({
  timer: 0,
  refTimer: null,

})

export const mutations = {
start_timer(state){
    state.refTimer = setInterval(()=>{state.timer = state.timer + 1}, 1000)
  },
  clear_timer(state){
    clearInterval(state.refTimer)
  },
}


export const actions = {
  

  initiate_timer({commit})
  {
    commit('start_timer')
  },

  clear_timer({commit})
  {
    commit('clear_timer')
  },
}

我收到错误

[vuex] 不要在突变处理程序之外改变 vuex 存储状态

它每隔一秒就会出现一次。所以这个函数被调用了,但是给了我这个错误。我怎样才能解决这个问题?

标签: javascriptvue.jsnuxt.js

解决方案


尝试避开设定的时间间隔,您可以通过在加载时获取当前日期时间来做到这一点。

//_index.vue
mounted() 
{
   this.loaded = new Date();
},
methods() {
    timeOnPage() {
        const diff = (this.loaded.getTime() - new Date().getTime()) / 1000;
        return Math.abs(Math.round(diff/60));
    }
},

destroyed() {
    this.$store.dispatch('business/action_to_post_request_with_timer', this.timeOnPage());
 }

推荐阅读