background

When developing medium and large applications with VUE, we usually use Vuex for state management, but because VUex maintains data in memory as JS objects, when the page is refreshed, the vuex data in memory will be lost. In many scenarios, we do not want to see this result

Questions raised

So how to implement vuex persistence, make it like localStorage, sessionStorag?

Build your own wheel

The general idea is to store the state of vuex, read the cache and register vuex during initialization, and see the following two solutions:

Scheme 1: Write a vuex plug-in

Vuex provides the function of plug-in. We can save the state in localStorage and sessionStorage during each mutation, and then read the stored state value to overwrite the initial value of state when the page is initialized

Scenario 2: Use the beforeUnload event

Beforeunload events may not be used too much, it is not a new feature, it is a very old event, and compatibility is very good (IE6 is compatible, you can believe it)

Beforeunload events are held before the page is unloaded. This event is triggered by actions such as refresh, return to another page, close, etc

This provides an alternative way of caching. Instead of recording each mutation, why not cache all states at once when the page is unloaded?

Based on this principle, I developed a plug-in called VUe-vuex-Persist

Third-party Solutions

Most third-party plug-ins are implemented based on vuex plug-ins.

The community also has some good plug-ins, such as Vuex-PersistedState