Usage scenarios
Recently, WHEN I was working on the login module of Vue project, I obtained the token after successful login and stored the token in VUEX. However, I found that the data in VUEX was restored to default after route switching, and the data in VUex was restored to default after page refreshing. Token is required for subsequent authentication, so we need to store the data in VUEX locally.
The vuex persistence plugin, vuex-PersistedState, is used
Vuex-persistedstate
The principle of this plug-in combines the storage method, but after unified configuration, there is no need to manually write the storage method
Usage:
-
The installation
npm install vuex-persistedstate --save Copy the code
-
Introduce the configuration in index.js under store
import { createStore } from 'vuex' import createPersistedState from 'vuex-persistedstate' export default createStore({ state: {},mutations: {},actions: {},modules: {},plugins: [ createPersistedState(), ], }) Copy the code
This is the default storage to localStorage, if you want to store to sessionStorage, the configuration is as follows
import { createStore } from 'vuex' import createPersistedState from 'vuex-persistedstate' export default createStore({ state: {},mutations: {},actions: {},modules: {},plugins: [ // Store vuex data to sessionStorage createPersistedState({ storage: window.sessionStorage, }), ], }) Copy the code
By default, all states are persisted. If you want to store the specified state, the configuration is as follows
import { createStore } from 'vuex' import createPersistedState from 'vuex-persistedstate' export default createStore({ state: {},mutations: {},actions: {},modules: {},plugins: [ // Store vuex data to sessionStorage createPersistedState({ storage: window.sessionStorage, reducer(val) { return { // Store only userData in state userData: val.userData } } }), ], }) Copy the code
API
Key: The key that stores persistent state (default VUex)
Paths: An array of any paths that are partially persistent states. If no path is given, the complete state is persistent. (Default: [])
Reducer: a function that will be called to persist the state based on a given path. These values are included by default.
Subscriber: a function that is called to set the mutation subscription. The default is store => handler => store.subscribe(handler)
Storage: instead of (or with) getState and setState. The default value is localStorage.
GetState: The function that will be called to rehydrate the previously persistent state. Storage is used by default.
SetState: The function that will be called to preserve the given state. Storage is used by default.
Filter: The function that will be called to filter any mutations that will eventually trigger the store with setState. Default: () => true
Refer to the link
Vuex Persistence plug-in (Vuex-PersistedState) solves the problem of Vuex data loss during page refresh