The scene again

When using Vuex to store state data, many of you have encountered such awkward situations:

Vuex is normal when the browser is not refreshed, rolled back, or advanced.

When you refresh, rollback, and advance (hereafter referred to as “SAO operation”), you find that the Vuex stored state values become the initial values!

Oh ~ no ~ 😫 this is not what I want!!

Very not easy from the API to take over the basic data, all lost ~ once back to the liberation before!

The reasons causing

Before we solve the problem, let’s get to the bottom of why this is the case.

Vuex is A JS project, the data is stored in memory, in SAO operation, will let Vuex reload, resulting in all the data restored to the initial value!

solution

Vuex will be lost during these operations. How about using localStorage, sessionStorage or even cookies to store Vuex persistently?

Of course the answer is yes!

If we go to the official website of Vuex, we can see that Vuex provides a very convenient plug-in function to help us solve this requirement ~

Nonsense not to say, directly on the code ~

// @/store/plugins/createPersistedPlugin.js
export default function createPersistedPlugin(options = { key: 'store' }) {
    return store= > {
        // 1. Check whether there are Vuex snapshots in 'sessionStorage'
        let sessionStore = JSON.parse(sessionStorage.getItem(options.key))
        // If no, use the initial value; otherwise, use the snapshot value
        sessionStore && store.replaceState(sessionStore)
        // If you are a temporary employee, you are fired
        sessionStore = null
        // 2. Listen for 'mutation' in 'Vuex'
        store.subscribe((mutation, state) = > {
            // 3. Dynamically store 'Vuex' snapshots to 'sessionStorage'
            sessionStorage.setItem(options.key, JSON.stringify(state))
        })
    }
}
Copy the code

Usage:

// @/store/index.js
import createPersistedPlugin from './plugins/createPersistedPlugin.js'
const persistedPlugin = createPersistedPlugin()

const store = new Vuex.Store({
  state,
  // Other code
  mutations,
  plugins: [persistedPlugin]
})

Copy the code

At this point, there is no need to worry about testers performing operations ~ 😄

conclusion

There is still room for improvement, such as:

  • willsessionStorageRefining tooptions, the corresponding persistent objects can be used according to different business scenarios, such aslocalStorage
  • inoptionsAdd one toexpiresExpiry date, atexpiresInternal effective, make the function more detailed
  • addinclude,excludeField,stateYou can selectively replace snapshots
  • and so on…
  • If you have betteridea, please leave a message

This is my first blog, write bad places also please give advice! Joke gently ~

Thank you very much! ☕ ️ ~