Persisting data with Vuex
Caution
This article is intended for Vue 2. Vue 3 is now available and is the recommended way to develop applications with Vue.
Common methods for storing this information include IndexDB, LocalStorage, and Cookies. These tools allow us, through various APIs, to store information in the browser being used at the time.
When using vuejs
with vuex
for managing state
, it facilitates the possibility of handling a centralized state throughout the application, which is reactive and integrates consistently with the rest of the framework. However, vuex
by default does not provide the ability to persist its information across browser sessions or even when refreshing the page. This leads us to use a plugin
for vuex
called vuex-persistedstate
.
Using vuex-persistedstate
in our project is extremely easy. We start by adding the module to our project with the following command:
$ npm install --save vuex-persistedstate
In the file where we load vuex
, we proceed to add the plugin:
import Vue from 'vue';
import Vuex from 'vuex';
// plugin to add
import createPersistedState from 'vuex-persistedstate';
Vue.use(Vuex);
const store = new Vuex.store({
state: {},
mutations: {},
actions: {},
getters: {},
// here we add the plugin
plugins: [createPersistedState()],
});
By placing this plugin as part of the store, from now on all the information saved in vuex will be persistent in the browser. By default, vuex-persistedstate
stores the state in LocalStorage. If you want to manually delete the stored information, you can do it from the browser's Developer Tools
. To do this, navigate to the Application
tab, under Storage
select Local Storage
, and delete the information you want to erase.
This is in case you want to completely empty the vuex. However, we can manipulate and delete information by code as we usually do when manipulating the state
.