在 Vuex 中,您可以使用本地存储(例如 localStorage)来缓存状态数据,并在页面刷新时将其加载回状态中。
首先,您需要在 Vuex 的 store 实例中定义一个方法,用于在页面刷新时从本地存储中加载数据:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
loadData ({ commit }) {
const data = window.localStorage.getItem('vuex-data')
if (data) {
commit('increment', JSON.parse(data).count)
}
}
}
})