Categories
JavaScript Answers

How to keep Vuex state on page refresh with Vue.js?

Spread the love

Sometimes, we want to keep Vuex state on page refresh with Vue.js.

In this article, we’ll look at how to keep Vuex state on page refresh with Vue.js.

How to keep Vuex state on page refresh with Vue.js?

To keep Vuex state on page refresh with Vue.js, we use the vuex-persistedstate package.

To install it, we run

npm install --save vuex-persistedstate

Then we use it by writing

import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

export default new Vuex.Store({
  plugins: [
    createPersistedState({
      storage: window.sessionStorage,
    }),
  ],
  state: {
    //....
  },
});

We add the createPersistedState plugin to the Vuex store and then set storage to window.sessionStorage to use session storage to save the Vuex store data.

Conclusion

To keep Vuex state on page refresh with Vue.js, we use the vuex-persistedstate package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *