首页 > 技术文章 > vue vuex 轮询调度

lankongclub 2019-08-30 11:15 原文

1.store 中定义轮询模块

export default new Vuex.Store({
  modules: {
    poll
  }
})

2. 页面轮询 && 全局轮询

页面轮询:仅单独页面的轮询,离开页面则取消轮询
全局轮询:项目启动便一直存在
原理:
轮询模块中的state变量有定时器变量以及轮询数据

const state = {
  num1: 0,
  numAll: 0,
  timer1: '',
  timerAll: ''
}

store 中的轮询模块同时会注册一个路由的前置守卫,进行清除所有页面轮询

import router from './../../router'
// 路由拦截
router.beforeEach((to, from, next) => {
  clearInterval(state.timer1)
  clearInterval(state.timer2)
  clearInterval(state.timer3)
  next()
})

3. 启动/取消轮询

每一个轮询都会配置一个取消的 mutaions

 methods: {
    start () {
      this.$store.dispatch('poll1')
    },
    stop () {
      this.$store.commit('clearAddNum1')
    }
  }

轮询模块中对应的 mutations 和 actions

const mutations = {
  clearAddNum1 () {
    clearInterval(state.timer1)
  }
}
const actions = {
  poll1 (store) {
    clearInterval(state.timer1)
    store.state.timer1 = setInterval(() => {
      store.commit('addNum1')
    }, 1000)
  }
}

4. 查询当前轮询 && 轮询数据

查询当前轮询,进入 Vue devtools 查看 Vuex 的commit事件。

页面使用计算属性监听所需数据

  computed: {
    num1 () {
      return this.$store.state.poll.num1
    }
  }

 

推荐阅读