As we all know, vuex is a plug-in for global state management. However, when the browser refreshes, the state in the memory will be released. The usual solution is to save the data locally and then assign the value to the state during vuex initialization. At this point, you can use vuex’s plug-in, Vuex-Solidification

Plugin address: Vuex-Solidification, welcome star

Plug-in principle

Vuex has a hook method: Store.subscribe ((mutation, state) => {}) this callback is called each time after the mutation method has executed, returning the state after execution

Method of use

The installation

npm install --save vuex-solidification
Copy the code

Import and Configuration

import Vue from 'vue' import Vuex from 'vuex' import count from './count/index.js'; import createPersistedState from 'vuex-solidification'; Vue.use(Vuex); const store = new Vuex.Store({ state: { count: { value: 0, num: 1 }, pos: 1 } plugins: [// Default storage state data to localStorage createPersistedState()]});Copy the code

Plug-in Parameters

createPersistedState({options}) : Function

Options include:

Key: String Key of the object stored in localStorage, sessionStorage. The default value is vuex

Local: Object and Session: Object represent the configuration of localStorage and sessionStorage respectively

Local and session include: include: Array and exclude: Array

Configuration example

CreatePersistedState ({local: {include: ['count.value']}}) /* Hook: {count: {value: 0,}} */ createPersistedState({local: {exclude: ['count.value']}}) /* Hook: {count: { num: 1 }, pos: 1 } */ createPersistedState({ session: { include: ['count.value']}}) {count: {value: 0,}} */ createPersistedState({session: {exclude: ['count.value']}}) /* SessionStorage {exclude: ['count.value']}}) 1 } */ createPersistedState({ session: { include: ['count'] }, local: { include: ['pos']}}) /* sessionStorage: {count: {value: 0, num: 1} 0} * /Copy the code

The code example

Check out the example on CodeSandbox.

Write in the last

Welcome to exchange, mention issue and PR,