There are instances in your Vue.js project where you need to share data between components. The global event bus could be the first idea to come to mind. While this may be enough for a simple application, its readability and reusability can become messy as the project grows.
Vuex to the rescue
Vuex works as a centralized store for all of your components. At the core of Vuex is its separation of concepts involved in state management while ensuring independence between views and states. This is solely responsible for ensuring readability and reusability of code for medium to large applications.
However, Vuex may not always be appropriate especially for small applications. A simple store pattern could be all you may need for such scenarios.
The problem
While Vuex enables data sharing between components, it doesn’t ensure retention beyond a page reload. This can only be achieved by taking advantage of long-term storage such as localStorage, sessionStorage and cookies among others.
The solution
Combining the short-term storage (Vuex) and long-term storage can be achieved by using a plugin. One such plugin is vuex-persister.
It is the smallest and fastest Vuex4, Vue3 and Nuxt — ready plugin that saves and rehydrates the state of your application between page reloads.
Installation
You first need to install the package through pnpm, yarn or npm.
pnpm add vuex-persister
or
yarn add vuex-persister
or
npm install vuex-persister
Usage
Import the package
import VuexPersister from 'vuex-persister'
Instantiate the instance
const vuexPersister = new VuexPersister({
//...
})
// new VuexPersister<State> for TypeScript
Initialize the store
const store = createStore({
state: {/* ... */},
// ...
plugins: [vuexPersister.persist]
})
// createStore<State> for TypeScript
For Nuxt.js
Define the plugin
// first create a plugin under the plugins folder ~/plugins/vuex-persister.js
import VuexPersister from 'vuex-persister'
export default ({ store }) => {
new VuexPersister({
// ...
}).persist(store)
}
Register plugin
// ~nuxt.config.js
export default {
/* ... other options */
plugins: [{ src: '~/plugins/vuex-persister.js', ssr: false }],
}
Conclusion
There is a lot you can do with the plugin, including obfuscating localStorage and using Cookies and sessionStorage among others. A list of API options is also available.
Top comments (1)
Great project. I will try to use it in my next Vue js project