自动刷新实现,vuex状态绑定

js 每5分钟刷新一次通过el-switch 来控制是否启用自动更新el-switch 通过 v-model 来绑定 store中的状态computed: {autoRefresh: {get() {return this.$store.state.dmx.mvAutoRefresh},set(value) {this.$store....

js 每5分钟刷新一次
通过el-switch 来控制是否启用自动更新
el-switch 通过 v-model 来绑定 store中的状态

computed: {
    autoRefresh: {
      get() {
        return this.$store.state.dmx.mvAutoRefresh
      },
      set(value) {
        this.$store.dispatch('dmx/setAutoRefresh', value)
      }
    },
    dmxTimer() {
      return this.$store.state.dmx.dmxTimer
    }
}

切换至其他页面时,清除自动刷新,进入时 再根据 autoRefresh 来判断是否加上定时刷新

  beforeDestroy() {
    clearInterval(this.dmxTimer)
    this.$store.dispatch('dmx/clearDmxTimer')
  },
  mounted() {
    this.autoRefreshHandler()
  },
  methods: {
    dmxtest() {
      console.log((new Date()) + '----')
    },
    autoRefreshHandler() {
      /** 定时器  **/
      if (this.autoRefresh) {
        if (this.dmxTimer == null) {
          const tmpDmxTimer = setInterval(this.dmxtest, this.dmxTimeout)
          this.$store.dispatch('dmx/setDmxTimer', tmpDmxTimer)
        }
      } else {
        if (this.dmxTimer != null) {
          clearInterval(this.dmxTimer)
          this.$store.dispatch('dmx/clearDmxTimer')
        }
      }
    }
}

dmx.js

// import Cookies from 'js-cookie'

const state = {
  // 首页是否自动刷新
  mvAutoRefresh: true,
  message: 'xxx',
  dmxTimer: null
}

const mutations = {
  setAutoRefresh: (state, val) => {
    state.mvAutoRefresh = val
  },
  updateMessage: (state, val) => {
    state.message = val
  },
  clearDmxTimer: (state) => {
    state.dmxTimer = null
  },
  setDmxTimer: (state, val) => {
    state.dmxTimer = val
  }
}

const actions = {
  setAutoRefresh: (context, val) => {
    context.commit('setAutoRefresh', val)
  },
  clearDmxTimer: (context) => {
    context.commit('clearDmxTimer')
  },
  setDmxTimer: (context, val) => {
    context.commit('setDmxTimer', val)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

本文标题为:自动刷新实现,vuex状态绑定

基础教程推荐