Persist Vuex State Across Browser Refreshes

Vuex serves as a centralized state management solution for Vue.js applications. However, the state stored in memory is lost when the browser page is refreshed. A common workaround involves using local storage (like localStorage or sessionStorage) to save the state and then rehydrating it when Vuex is initialized. This process can be cumbersome. The vuex-persistedstate plugin offers a more streamlined solution.

Plugin Mechanism

The vuex-persistedstate plugin leverages Vuex's store.subscribe hook. This hook is invoked after every mutation is committed, providing access to the updated state. The plugin intercepts this state and persists it using the browser's storage mechanisms.

Installation and Basic Usage

First, install the plugin:

npm install --save vuex-persistedstate

Then, integrate it into your Vuex store configuration:

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

Vue.use(Vuex);

const store = new Vuex.Store({
  // ... your existing store configuration (state, mutations, actions, etc.)
  plugins: [
    // This line enables persistence for all state by default, using localStorage
    createPersistedState()
  ]
});

export default store;

Configuration Options

The createPersistedState function accepts an optional options object to customize persistence behavior.

keyA string that specifies the key under which the Vuex state will be stored in localStorage or sessionStorage. The default key is 'vuex'.

local and session Objects These options allow you to configure persistence separately for localStorage (local) and sessionStorage (session). Both local and session can accept include or exclude arrays.

  • include: Array: Specifies which parts of the state should be persisted.
  • exclude: Array: Specifies which parts of the state should not be persisted.

Let's consider a sample state:

state: {
  userProfile: {
    name: 'Alice',
    email: 'alice@example.com',
    settings: {
      theme: 'dark'
    }
  },
  userId: 123
}

Example 1: Persisting specific state properties with include

createPersistedState({
  local: {
    include: ['userProfile.name', 'userId']
  }
});

This configuration will store only the userProfile.name and userId in localStorage. The resulting localStorage entry would look like:

{
  "userProfile": {
    "name": "Alice"
  },
  "userId": 123
}

Example 2: Excluding specific state properties with exclude

createPersistedState({
  local: {
    exclude: ['userProfile.email']
  }
});

This configuration will persist all state properties except userProfile.email to localStorage:

{
  "userProfile": {
    "name": "Alice",
    "settings": {
      "theme": "dark"
    }
  },
  "userId": 123
}

Similar include and exclude option are available for session storage.

Example 3: Combining local and session storage

createPersistedState({
  local: {
    include: ['userId']
  },
  session: {
    include: ['userProfile']
  }
});

With this setup:

  • localStorage will store: {"userId": 123}
  • sessionStorage will store: {"userProfile": {"name": "Alice", "email": "alice@example.com", "settings": {"theme": "dark"}}}

Custom Storage Engines

If localStorage or sessionStorage are not suitable, you can implement custom storage solutions. For instance, to use cookies:

import { Store } from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import * as Cookies from 'js-cookie'; // Assuming you use the js-cookie library

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: key => Cookies.get(key),
        setItem: (key, value) => Cookies.set(key, value, { expires: 3, secure: true }), // Example: expires in 3 days
        removeItem: key => Cookies.remove(key)
      }
    })
  ]
});

Any object adhering to the storage protocol (having getItem, setItem, and removeItem methods) can be passed to the storage option. For example, you can directly use window.sessionStorage or window.localStorage if you don't need the filtering capabilities:

createPersistedState({ storage: window.sessionStorage });

For more advanced configurations and features, refer to the official plugin documentation.

Tags: Vuex javascript frontend state management local storage

Publicado em 6-18 19:21