SoFunction
Updated on 2025-03-10

Vuex plugin vuex-persistedstate data persistent storage operation

1. Install plug-ins

yarn add vuex-persistedstate
// ornpm install --save vuex-persistedstate

2. How to use

usesessionStorageCache abovestatedata,keyNamedstore

import Vue from 'vue'
import Vuex from 'vuex'
// Introduce plug-insimport createPersistedState from "vuex-persistedstate";
(Vuex)
const state = {};
const mutations = {};
const actions = {};
const store = new ({
	state,
	mutations,
	actions,
    /* vuex data persistence configuration */
	plugins: [
		createPersistedState({
            // Storage method: localStorage, sessionStorage, cookies Default: localStorage			storage: ,
            // The key value of the stored key			key: "store",
			render(state) {
                // Data to be stored: This project uses the es6 extension operator to store all data in the state				return { ...state };
			}
		})
	]
});
export default store;

3. Cache some data under State

import Vue from 'vue'
import Vuex from 'vuex'
// Introduce plug-insimport createPersistedState from "vuex-persistedstate";
(Vuex)
const state = () => {
    return {
        token: '',
        uid: ''
    }
}
const store = new ({
    // ...
    plugins: [createPersistedState({
        storage: ,
        reducer(val) {  // val is the state above            return {
                // Only store tokens in state, not cache uids                token: 
            }
        }
    })]
})

4. Cache the state of a specified module under multiple Vuex modules, and implement it by modifying the path configuration.

/* user-module */
export const user = {
    state: {
        token: '',
        role: ''
    }
}
/* profile-module */
export const profile = {
    state: {
        name: '',
        company: ''
    }
}
/* */ in the modules directory
import user from './user'
import profile from './profile'
export default {
    user,
    profile
}
/*  */
import modules from './modules'
let store = new ({
    modules,
    plugins: [
        createPersistedState({
            key: 'zdao',
            paths: ['user'] // This will only cache the state value under user        })
    ]
})

This is the article about Vuex-persistedstate data persistent storage. For more related contents of vuex-persistedstate data persistent storage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!