Installation
Install the plugin with your preferred package manager:
sh
bun i pinia-plugin-state-persistence
sh
pnpm add pinia-plugin-state-persistence
sh
npm i pinia-plugin-state-persistence
sh
yarn add pinia-plugin-state-persistence
Vue 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 pinia
Notes:
- Default Storage: The default storage mechanism is
localStorage
. To use a custom storage, replace thestorage
option. - Imports: Ensure the imports are correct for both
pinia
andpinia-plugin-state-persistence
. - Default Options:
serialize
anddeserialize
: The default behavior isJSON.stringify
andJSON.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: true
to 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-persistence
package is installed. - Verify that
pinia
is properly installed and initialized in your project. - Check browser compatibility for the chosen
storage
option (localStorage
or other custom implementations).