vuex 數據持久化,防止刷新丟失


import Vue from 'vue'
import Vuex from 'vuex'
import router from '../routers'

Vue.use(Vuex)
import { getUserInfo } from '../api/index.js'

const store = new Vuex.Store({
  state: {
    userInfo: {}, // 用戶信息
    remain_time: 300,
    remain_interval: null // 定時器
  },
  mutations: {
    // 時間減少
    TIME_SUBTRACT(state) {
      if (state.remain_time > 0) {
        state.remain_time--
      } else {
        clearInterval(state.remain_interval)
        state.remain_interval = null // 定時器清空
        state.remain_time = 300 // 重置時長
        router.push('/')
      }
    },
    // 清空時間
    TIME_CLEAR(state) {
      state.remain_time = 0
      router.push('/')
    },
    // 信息更新
    USER_UPDATE(state, payload) {
      state.userInfo = payload
    }
  },
  actions: {
    // 設置定時器
    startInterval({ commit, state }) {
      state.remain_interval = setInterval(function() {
        commit('TIME_SUBTRACT')
      }, 1000)
    },
    // 獲取信息
    getUserInfo({ commit }) {
      getUserInfo().then(res => {
        console.log('res_獲取用戶信息', res)
        commit('USER_UPDATE', res.data)
      })
    }
  }
})

// 從sessionStorage中取值
if (sessionStorage.getItem('store')) {
  store.replaceState(
    Object.assign(
      {},
      store.state,
      JSON.parse(sessionStorage.getItem('store'))
    )
  )
  if (store.state.remain_time > 0 && store.state.remain_interval !== null) {
 store.dispatch('startInterval') }
   sessionStorage.removeItem('store')
}

// 監聽頁面刷新,將數據全部保存到sessionStorage中
window.addEventListener('beforeunload', () => {
  sessionStorage.setItem('store', JSON.stringify(store.state))
})

export default store

思路:

1、store需要先被實例化

2、需要持久化保存的數據,自己隨便起名就能存,我這里默認是保存所有數據了

3、牽扯到定時器的,刷新頁面被自動清除了,需要自己重新激活

以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM