Installation
Install the plugin with your preferred package manager:
sh
bun i pinia-plugin-state-persistencesh
pnpm add pinia-plugin-state-persistencesh
npm i pinia-plugin-state-persistencesh
yarn add pinia-plugin-state-persistenceVue Installation
Add the plugin to your Pinia store. Ensure that your project is set up with TypeScript for better type safety and developer experience.
Example Setup
ts
// @filename: pinia.ts
import { createPinia } from 'pinia'
import { createStatePersistence } from 'pinia-plugin-state-persistence'
// Initialize Pinia
const pinia = createPinia()
// Use the plugin with default localStorage
pinia.use(createStatePersistence())
export default piniaNotes:
- Default Storage: The default storage mechanism is
localStorage. To use a custom storage, replace thestorageoption. - Imports: Ensure the imports are correct for both
piniaandpinia-plugin-state-persistence. - Default Options:
serializeanddeserialize: The default behavior isJSON.stringifyandJSON.parse. You can customize these functions for specific serialization needs.
- Plugin Usage: This plugin must be applied to your Pinia instance before using it in your application.
- Debug Mode: Set
debug: trueto see logs during development.
Add this file to your Pinia setup (e.g., src/store/pinia.ts) and import it in your main application file to initialize the Pinia store with persistence:
ts
// @filename: main.ts
import { createApp } from 'vue'
import App from './App.vue'
import pinia from './store/pinia'
const app = createApp(App)
// Use Pinia with persistence
app.use(pinia)
app.mount('#app')Usage
Enable the new persist option by setting it to true when defining your store.
ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useStore = defineStore(
'example',
() => {
const exampleState = ref('example value')
return { someState }
},
{
persist: true,
},
)ts
import { defineStore } from 'pinia'
export const useStore = defineStore('example', {
state: () => {
return {
exampleState: 'example value',
}
},
persist: true,
})Troubleshooting:
- Ensure the
pinia-plugin-state-persistencepackage is installed. - Verify that
piniais properly installed and initialized in your project. - Check browser compatibility for the chosen
storageoption (localStorageor other custom implementations).