Universal Storage Utilities for Nuxt.js based on @nuxt-community/auth-module
@nuxtjs/universal-storage dependency using yarn or npm to your projectyarn add @nuxtjs/universal-storage
OR
npm install @nuxtjs/universal-storage --save
@nuxtjs/universal-storage to the modules section of your nuxt.config.js file{
modules: [
'@nuxtjs/universal-storage',
],
storage: {
}
}
Options are defined as following:
storage: {
vuex, // boolean or {namespace}
localStorage, // boolean or {prefix}
cookie, // boolean or {prefix, options}
initialState, // Object {}
ignoreExceptions //
}
and default to the following values:
{
vuex: {
namespace: 'storage'
},
cookie: {
prefix: '',
options: {
path: '/'
}
},
localStorage: {
prefix: ''
},
ignoreExceptions: false,
}
Since version 0.4.0 this module allows full state synchronisation with cookies, localStorage and initialState as a default value. That allows for a very neat usage pattern:
For example, if you have an initialState like the following in your nuxt.config.js file:
storage: {
initialState: { testParam: false }
}
then in my component I can simply declare (with decorators)
@State(s => s.storage.testParam)
testParam
or (with mapState)
computed: mapState({
testParam: s => s.storage.testParam
})
Afterwards you can get the computed property testParam with whatever value it had in your last session and on change you just have to call this.$storage.setUniversal("testParam", newVal) to get the new value saved.
Private state is suitable to keep information not being exposed to the Vuex store. This helps prevent stealing tokens from the SSR response HTML.
If the key name starts with _ then that value is kept separate in the memory storage and not exposed to the Vuex store like the rest of the values.
For example:
$storage.setState("_password", "alpha1")
$storage.getUniversal(key)$storage.setUniversal(key, value)$storage.syncUniversal(key, defaultValue)$storage.removeUniversal(key)$storage.getState(key)$storage.setState(key, value)$storage.removeState(key)$storage.watchState(key, fn)$storage.getLocalStorage(key)$storage.setLocalStorage(key, value)$storage.removeLocalStorage(key)$storage.getCookies()$storage.getCookie(key)$storage.setCookie(key, value)$storage.removeCookie(key)yarn install or npm installyarn run dev or npm run devhttp://localhost:3000