持久化插件
原创2026/3/5小于 1 分钟
pinia 有个副作用,就是无法持久化,在浏览器刷新重置之后,会全部回复默认,这时候,我们可以利用插件实现本地持久化存储
安装
npm install --save pinia-plugin-persistedstate引入持久化插件
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from './App.vue'
import router from './router'
const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app.use(pinia)
app.use(router)
app.mount('#app')使用持久化插件
import { ref, computed } from 'vue'
import { defineStore, acceptHMRUpdate } from 'pinia'
export const useCounterStore = defineStore(
'counter',
() => {
const count = ref(1)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
const countX3 = () => {
count.value = count.value * 3
}
return { count, doubleCount, increment, countX3 }
},
{
persist: true,
},
)
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useCounterStore, import.meta.hot))
}此时,回到应用中,进行修该操作,刷新页面查看效果
<template>
<p>count:{{ count }}</p>
<p>doubleCount:{{ doubleCount }}</p>
<button @click="countAdd">count ++</button>
</template>
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'
const counterStore = useCounterStore()
const { count, doubleCount } = storeToRefs(counterStore)
const countAdd = () => {
counterStore.increment()
}
</script>至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。