Vuex is great for handling state in your app, but sometimes you want it to persist across multiple pages loads and whatnot. The naive way to do this (and I’m as guilty of it as any,) is to add a quick little function call in each mutation to save the current state of your app to localStorage
. Not exactly a great solution, but just not-bad-enough that it often suffices. But there’s a better way. Vuex actually has plugin support, and vuex-persist is a teeny-tiny plugin that automatically syncs your store with localStorage
, or any other storage method supporting the getItem/setItem/clear
interface.
Install vuex-persist in your Vue.js project.
Now, wherever you initialize your store (and this may vary a lot from project to project,) import vuex-persist
and initialize it as a plugin for Vuex
.
The reducer
option allows you to only store certain sections of the state. It’s a simple function that gets passed the full state tree and is expected to return an object containing only the parts of the state tree you’d like to keep. This shouldn’t, however, modify the structure of the tree, or otherwise it can’t be re-loaded.
Sometimes certain mutations shouldn’t trigger a store sync. For example, if you have a mutation called every few milliseconds, updating the storage every time it’s called would cause a huge degredation in performance. vuex-persist
provides a filter function to address this exact use-case. You can filter out any mutations you don’t want to cause a storage update, or create a whitelist of mutations you want to keep.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
“keepThisModule” is a misleading name. One might think this store is module based. “reducer” option is for root state properties only. Use “modules” config option to whitelist actual modules.