Implement a simple version of vuex persistence tool

background

Recently, when developing applet projects with uni-app, some content that needs to be persisted can't be called like state in other vuex, so think about implementing something like vuex-persistedstate plug-in yourself. It doesn't seem like a lot of code

Preliminary ideas

The first thought is naturally the watcher mode of vue.Hijack content that needs to be persisted, and execute the persistence method when the content changes.Get a dep and observer first, direct observer needs a persisted state, and pass in callbacks for get and set:

However, it soon became apparent that if a={b:{c:d:{e:1}} was stored, the operation would normally B e xxstorage('a',a). Next, whether a.b, a.b.c, or a.b.c.d.e was changed, xxstorage('a',a) would need to B e re-executed, that is, the entire object tree would b e re-persisted regardless of which descendant node of a was changed, so it was monitored.After a descendant node of a root node changes, it is necessary to find the root node first, and then re-persist the items corresponding to the root node.The next first question is how to find the parent of a changing node.

Reconstructing state Tree

It is too complex to find a moving node down the state and confirm the changing item based on the path where the node was found.If you add a pointer to each item in the state while observer, can you find the corresponding root node along the pointer to the parent node when the descendant node changes?To avoid the new pointer being traversed, Symbol was chosen, so the dep part changed as follows:

But the problem is that object s can be automatically persisted. When an array is operated on by push and pop, the address of the array is unchanged. DefneProperty can't detect this change at all (unfortunately, Proxy compatibility is too poor and Android doesn't support it directly in the applet).Of course, each time you manipulate an array, reassigning the array solves the problem, but it's too inconvenient to use.

Binding when changing arrays

The same way to solve the array problem is to refer to the vue source processing, override the array's'push','pop','shift','unshift','splice','sort','reverse'methodsWhen an array operates on an array in these seven ways, manually trigger part of the set to update the story content

Add Anti-Shake

When vuex is persisted, it is easy to encounter situations where state s are frequently manipulated. If you keep updating storage, performance will be poor