Introduction

In Vue.js applications using Vuex, it's common to want to persist the state data between page refreshes. This ensures that user data and application state are maintained. Two popular options for state persistence are LocalStorage and Cookies. In this guide, we'll explore how to implement state persistence with LocalStorage and Cookies in a Vuex store and provide sample code to demonstrate the process.


Sample Code

Let's create a Vue.js application with Vuex state persistence using LocalStorage and Cookies:


<div id="app">
<p>Counter: {{ counter }}</p>
<button @click="incrementCounter">Increment Counter</button>
<button @click="resetCounter">Reset Counter</button>
const store = new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment(state) {
state.counter++;
},
reset(state) {
state.counter = 0;
}
},
plugins: [
(store) => {
// Load state from LocalStorage
if (localStorage.getItem('vuexState')) {
store.replaceState(JSON.parse(localStorage.getItem('vuexState')));
}
// Subscribe to state changes and save to LocalStorage
store.subscribe((mutation, state) => {
localStorage.setItem('vuexState', JSON.stringify(state));
});
// Subscribe to state changes and save to Cookies
store.subscribe((mutation, state) => {
document.cookie = `vuexState=${JSON.stringify(state)}`;
});
}
]
});
const app = new Vue({
el: '#app',
store,
computed: Vuex.mapState(['counter']),
methods: Vuex.mapMutations(['increment', 'reset']),
beforeCreate() {
// Load state from Cookies
const cookies = document.cookie.split('; ');
for (const cookie of cookies) {
const [key, value] = cookie.split('=');
if (key === 'vuexState') {
store.replaceState(JSON.parse(value));
break;
}
}
}
});

In this code:

  • We create a Vue component with a counter and buttons to increment and reset it.
  • We set up a Vuex store with a `counter` state and corresponding mutations.
  • Within the store, we use Vuex plugins to load and save the state to LocalStorage and Cookies.
  • We subscribe to state changes and update LocalStorage and Cookies whenever the state changes.
  • In the Vue instance, we use computed properties and methods mapped from the store to access and modify the state.
  • We also load the state from Cookies during component creation.