vuex页面刷新保存数据到sessionstorage中,以及需要注意的问题

1、vuex页面刷新保存数据到sessionstorage中 (参考其他博客https://blog.csdn.net/guzhao593/article/details/81435342),在App.vue中添加如下代码

    created () {
      //在页面加载时读取sessionStorage里的状态信息
      if (sessionStorage.getItem("store") ) {
        this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(sessionStorage.getItem("store"))))
      }

      //在页面刷新时将vuex里的信息保存到sessionStorage里
      window.addEventListener("beforeunload",()=>{
        sessionStorage.setItem("store",JSON.stringify(this.$store.state))
      })
    }

2、注意可能会出现的问题

function getChartData (state, key) {
  if (state.curveData.hasOwnProperty(key)) {
    return state.curveData[key]
  } else {
    return false
  }
}

const getters = {
  renderProjectInfo (state) {
    // console.log(state.renderProjectInfo)
    return state.projectInfo
  },
  getDeviceInfo (state) {
    return state.deviceInfo
  },
  getTimerFlag (state) {
    return state.timerFlag
  },
  getCurveData (state) {
    console.log('getCurveData: ', state.curveData)
    return state.curveData
  },
  getFaultData (state) {
    return state.faultData
  },
  getSwitchProject (state) {
    return state.switchProject
  },
  getProjectId (state) {
    return state.projectId
  }
}

const mutations = {
  setProjectInfo (state, projectInfo) {
    state.projectInfo = projectInfo
  },
  setTimerFlag (state, timerFlag) {
    state.timerFlag = timerFlag
  },
  saveProjectId (state, projectId) {
    state.projectId = projectId
  },
  start (state) {
    const url = 'machine/detail/' + state.projectId
    console.log('URL: ', url)
    startTimer(state, url)
  },
  stop (state) {
    closeTimer(state)
  },
}

const actions = {
  setProjectInfo (context, data) {
    context.commit('setProjectInfo', data)
  },
  setTimerFlag (context, data) {
    context.commit('setTimerFlag', data)
  },
  getProjectId (context, projectId) {
    context.commit('saveProjectId', projectId)
  },
  switchedProject (context, switched) {
    context.commit('setSwitchProject', switched)
  }
}

export default {
  namespaced: true, // 用于在全局引用此文件里的方法时标识这一个的文件名
  state,
  getters,
  mutations,
  actions
}

需要注意,在getters、mutations,以及自定义的函数中,如果有用到state中的数据,那么函数必须带参数state,使用state中的数据的方式为(state.state中的变量名),例如上面代码中的函数getChartData的方式。

你可能感兴趣的:(vue2,web前端,vuex)