NuxtJS: Persist Vuex State with vuex-persist


Package vuex-persist

Current version: 3.1.3
Link: https://www.npmjs.com/package/vuex-persist

Features

  • 📦 NEW in v1.5
    • distributed as esm and cjs both (via module field of package.json)
    • better tree shaking as a result of esm
  • 🎗 NEW IN V1.0.0
    • Support localForage and other Promise based stores
    • Fix late restore of state for localStorage
  • Automatically save store on mutation.
  • Choose which mutations trigger store save, and which don’t, using filter function
  • Works perfectly with modules in store
  • Ability to save partial store, using a reducer function
  • Automatically restores store when app loads
  • You can create mulitple VuexPersistence instances if you want to –
    • Save some parts of the store to localStorage, some to sessionStorage
    • Trigger saving to localStorage on data download, saving to cookies on authentication result

Compatibility
VueJS – v2.0 and above
Vuex – v2.1 and above

Work with NuxtJS

Install:

D:\Nuxt\demo>npm i vuex-persist
npm WARN bootstrap@4.5.3 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ vuex-persist@3.1.3
added 2 packages from 2 contributors and audited 1709 packages in 16.905s

78 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Create plugin: file plugins/vuex-persist.js

import VuexPersistence from 'vuex-persist'
 
export default ({ store }) => {
  new VuexPersistence({
    key: 'vuex', // The key to store the state on in the storage provider.
    storage: window.localStorage, // or window.sessionStorage or localForage    
  }).plugin(store);
}

Config NuxtJS, file nuxt.config.js

export default {
  ...
  // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
  plugins: [
    { src: '~/plugins/vuex-persist', ssr: false }
  ],
   ...
}

Done!

Leave a Reply