vue3 pinia vuex-persistedstate的使用
时间: 2023-11-01 19:16:03 浏览: 110
Vue3中的状态管理库Pinia和Vuex-Persistedstate插件可以一起使用,用于在浏览器的localStorage中存储和恢复Vuex或Pinia状态。
首先,你需要安装Pinia和Vuex-Persistedstate插件:
npm install pinia vuex-persistedstate
然后,在你的应用程序中,创建一个Pinia store或Vuex store。这里以Pinia为例:
import { createPinia } from 'pinia'
const pinia = createPinia()
pinia.store({
id: 'store',
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++
}
}
})
接下来,在您的应用程序中,您需要导入Vuex-Persistedstate插件并将其添加到Pinia插件中:
import { createPinia } from 'pinia'
import VuexPersistence from 'vuex-persistedstate'
const pinia = createPinia()
pinia.use(VuexPersistence, {
storage: window.localStorage
})
pinia.store({
id: 'store',
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++
}
}
})
在这里,我们将Vuex-Persistedstate插件添加到Pinia插件中,并将storage属性设置为window.localStorage,以便状态可以保存在本地存储中。
现在,当您使用increment操作时,状态将自动保存在本地存储中。当您刷新页面或重新加载应用程序时,状态将自动从本地存储中恢复。
相关推荐

















