Stashing Vue components data
A small mixin to make “rememberable” data
Hello there!
It’s no long-read there, I’ll share just a small mixin for one simple case :)
P.S. I had a little negative feedback about my previous post without any argumentation (even invalid). So, the note to people who’ll say “scratch that” — please, walk your way
Situation
So, imagine that we have component with some selection logic. E.g. products selector with products from store. And here is one moment — we want to remember users’s choice if he switches page:
But here is one problem. active
may be not related to application at all (leave examples with products cart). We can have more than one component with products selection and all of them are not connected in any way.
So, we’ll do this:
Typical boilerplate code that I don’t like. I had approximately 10–15 such things in my previous project. Moreover, sometimes I see examples when it’s stored in vuex even if it’s not related to vuex.
What if we do something to choose some component data to be rememberable?
Something like.. This:
This is what I did — just a mixin that allows you to define stashable data in stash
property. It automatically saves all data from stash to localStorage before component destroy and window unload
Also, if you have 2+ instances of one component, its stashed data will be synced.
You can find it here: vue-data-stash
Note about vuex
You should store data like forms, selectable things in vuex only if it should be used throughout the application (like everything should).
If it’s OK, store this data in vuex. Otherwise, just use stash in components
That’s all :)