Persisting store state means saving your app's data so it stays even after you refresh the page or close the browser. This helps users keep their progress or settings without losing them.
Persisting store state in Vue
import { createStore } from 'vuex' import createPersistedState from 'vuex-persistedstate' const store = createStore({ state() { return { count: 0 } }, mutations: { increment(state) { state.count++ } }, plugins: [createPersistedState()] }) export default store
The vuex-persistedstate plugin automatically saves and loads the store state to localStorage.
You add it in the plugins array when creating the store.
plugins: [createPersistedState()]
plugins: [createPersistedState({ storage: window.sessionStorage })]user and settings parts of the store state.plugins: [createPersistedState({ paths: ['user', 'settings'] })]This Vue app uses Vuex with the persisted state plugin. When you click the button, the count increases and is saved. Refreshing the page keeps the count value.
import { createApp } from 'vue' import { createStore } from 'vuex' import createPersistedState from 'vuex-persistedstate' const store = createStore({ state() { return { count: 0 } }, mutations: { increment(state) { state.count++ } }, plugins: [createPersistedState()] }) const app = createApp({ computed: { count() { return store.state.count } }, methods: { increment() { store.commit('increment') } }, template: ` <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <p>Refresh the page and the count stays the same.</p> </div> ` }) app.use(store) app.mount('#app')
Persisted state usually uses localStorage, which keeps data even after closing the browser.
Be careful not to store sensitive data in localStorage because it is accessible by JavaScript.
You can customize which parts of the store to save using the paths option.
Persisting store state saves your app data so it stays after refresh or closing the browser.
Use the vuex-persistedstate plugin to easily add this feature.
You can choose where and what to save for better control and security.