vue项目中刷新(F5)会重置Vuex state,配置持久化state

因为 state 存储在内存中,刷新后内存清空,state就会初始化

image


持久化state方法:

1:localStorage在页面刷新时不会丢失,所以第一次写入state时可以手动往localStorage中存一份,在刷新页面时从localStorage 恢复

2:使用 vuex-persistedstate 插件,自动持久化

npm install vuex-persistedstate

在src/store/index.js中配置

// src/store/index.js
import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
})

 

posted @ 2026-03-04 11:40  何以平天下  阅读(13)  评论(0)    收藏  举报