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 } }