Vue and Vuex plugin to persistence data with localStorage/sessionStorage

Overview

vuejs-storage

Vue.js and Vuex plugin to persistence data with localStorage/sessionStorage

npm npm GitHub Workflow Status codecov

Purpose

This plugin provide a simple binding with localStorage and sessionStorage (or something similar) to Vue and Vuex.

It has no dependencies, so it is really small.

  • .js size: 5.75KB (1.7KB gzipped)
  • .min.js size: 2.21KB (1.1KB gzipped)

Usage

//in webpack environment:
import vuejsStorage from 'vuejs-storage'
//in browser script tag:
const vuejsStorage = window.vuejsStorage

Vue.use(vuejsStorage)

//vue example
new Vue({
  //...
  data: {
    count: 0,
    text: ''
  },
  storage: {
    keys: ['count'],
    //keep data.count in localStorage
    namespace: 'my-namespace'
  }
})

//vuex example
const store = new Vuex.Store({
  //state...
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  plugins: [
    vuejsStorage({
      keys: ['count'],
      //keep state.count in localStorage
      namespace: 'my-namespace',
      driver: vuejsStorage.drivers.sessionStorage
      //if you want to use sessionStorage instead of localStorage
    })
  ]
})

Nested key

data: {
  a: {
    b: 1,
    c: 2
  }
},
storage: {
  namespace: 'test',
  keys: ['a.b']
  //only keep a.b in localStorage
}

Vuex modules

state: {
  a: 1
},
modules: {
  moduleA: {
    state: {
      a: 2
    }
  }
},
plugins: [
  vuejsStorage({
    namespace: 'test',
    keys: ['moduleA','a']
    // keep both root's state.a & moduleA's state
  })
]

Multiple storage

data: {
  a: 1,
  b: 2
},
storage: [
  {
    namespace: 'test',
    keys: ['a']
  },
  {
    namespace: 'test',
    keys: ['b'],
    driver: vuejsStorage.drivers.sessionStorage
  }
]

API

vuejsStorage

Vue plugin

Vue.use(vuejsStorage)

vuejsStorage(option)

Create a Vuex plugin

const vuexplugin = vuejsStorage(/* option object*/)

option

Option object, can be used when create Vuex plugin or in Vue option storage field

{
  keys: [], //array of string
  /*
  this option is different when use in vue and vuex
  when used in Vue constructor option, keys means which data should be keep in localStorage
  when used in Vuex plugin, keys mean which state should be keep in localStorage
  */
  driver: vuejsStorage.drivers.sessionStorage, //any object has 'set','get','has' api, default: vuejsStorage.drivers.localStorage
  namespace: 'ns', //a string, REQUIRED
  merge: _assign //a function to merge object like Object.assign, default: internal implementation(src/assign.ts)
}

Examples

Comments
  • Update bili to the latest version 🚀

    Update bili to the latest version 🚀

    The devDependency bili was updated from 3.4.2 to 4.3.0.

    This version is not covered by your current version range.

    If you don’t accept this pull request, your project will work just like it did before. However, you might be missing out on a bunch of new features, fixes and/or performance improvements from the dependency update.


    Find out more about this release.

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 22
  • Vuex modules strange behaviour - Typescript

    Vuex modules strange behaviour - Typescript

    the problem

    Hi i am having some problem with your plugin since i separated my vuex store into modules. it does not take the state within the getters.

    the code

    here you can find a gist with my code

    consideration

    it is fairly possible that i have done some kind of errors since is the first time i work with typescript, but everything work as expected if i comment the plugin array within store.ts

    bug fixed docs 
    opened by AndreaMinato 21
  • Update rollup-plugin-typescript2 to the latest version 🚀

    Update rollup-plugin-typescript2 to the latest version 🚀

    The devDependency rollup-plugin-typescript2 was updated from 0.19.3 to 0.20.0.

    This version is not covered by your current version range.

    If you don’t accept this pull request, your project will work just like it did before. However, you might be missing out on a bunch of new features, fixes and/or performance improvements from the dependency update.


    Find out more about this release.

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 19
  • Update karma to the latest version 🚀

    Update karma to the latest version 🚀

    The devDependency karma was updated from 3.1.4 to 4.0.1.

    This version is not covered by your current version range.

    If you don’t accept this pull request, your project will work just like it did before. However, you might be missing out on a bunch of new features, fixes and/or performance improvements from the dependency update.


    Release Notes for v4.0.1

    Bug Fixes

    Commits

    The new version differs by 20 commits.

    • c7ebf0b chore: release v4.0.1
    • c190c4a chore: update contributors
    • 375bb5e fix(filelist): correct logger name. (#3262)
    • c43f584 fix: remove vulnerable dependency combine-lists (#3273)
    • 4ec4f6f fix: remove vulnerable dependency expand-braces (#3270)
    • d5df723 fix(browser): allow updating total specs count (#3264)
    • c277a6b fix(launcher): Debug Child Processes exit signal (#3259)
    • bd95d89 chore: upgrade log4js to v4.0.0 (#3257)
    • 5a47718 chore: release v4.0.0
    • 56cc239 chore: update contributors
    • d59cf35 refactor(watcher): Make watcher injectable to support 3rd-party watchers (#3254)
    • 988b901 chore(license): Update copyright notice to 2019 [ci skip] (#3250)
    • 571191c fix(client): fix issue with loaded on safari 10 (#3252)
    • 376142e refactor(fileList): refactor with async/await (#3247)
    • acdd2dc refactor(server): refactor start method to use async/await (#3245)

    There are 20 commits in total.

    See the full diff

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 16
  • Update mocha to the latest version 🚀

    Update mocha to the latest version 🚀

    The devDependency mocha was updated from 5.2.0 to 6.0.0.

    This version is not covered by your current version range.

    If you don’t accept this pull request, your project will work just like it did before. However, you might be missing out on a bunch of new features, fixes and/or performance improvements from the dependency update.


    Release Notes for v6.0.0

    6.0.0 / 2019-02-18

    💥 Breaking Changes

    • #3149: Drop Node.js v4.x support (@outsideris)
    • #3556: Changes to command-line options (@boneskull):
      • --grep and --fgrep are now mutually exclusive; attempting to use both will cause Mocha to fail instead of simply ignoring --grep
      • --compilers is no longer supported; attempting to use will cause Mocha to fail with a link to more information
      • -d is no longer an alias for --debug; -d is currently ignored
      • #3275: --watch-extensions no longer implies js; it must be explicitly added (@TheDancingCode)
    • #2908: tap reporter emits error messages (@chrmod)
    • #2819: When conditionally skipping in a before hook, subsequent before hooks and tests in nested suites are now skipped (@bannmoore)
    • #627: Emit filepath in "timeout exceeded" exceptions where applicable (@boneskull)
    • #3556: lib/template.html has moved to lib/browser/template.html (@boneskull)
    • #2576: An exception is now thrown if Mocha fails to parse or find a mocha.opts at a user-specified path (@plroebuck)
    • #3458: Instantiating a Base-extending reporter without a Runner parameter will throw an exception (@craigtaub)
    • #3125: For consumers of Mocha's programmatic API, all exceptions thrown from Mocha now have a code property (and some will have additional metadata). Some Error messages have changed. Please use the code property to check Error types instead of the message property; these descriptions will be localized in the future. (@craigtaub)

    📠 Deprecations

    These are soft-deprecated, and will emit a warning upon use. Support will be removed in (likely) the next major version of Mocha:

    • -gc users should use --gc-global instead
    • Consumers of the function exported by bin/options should now use the loadMochaOpts or loadOptions (preferred) functions exported by the lib/cli/options module

    Regarding the Mocha class constructor (from lib/mocha):

    • Use property color: false instead of useColors: false
    • Use property timeout: false instead of enableTimeouts: false

    All of the above deprecations were introduced by #3556.

    mocha.opts is now considered "legacy"; please prefer RC file or package.json over mocha.opts.

    🎉 Enhancements

    Enhancements introduced in #3556:

    • Mocha now supports "RC" files in JS, JSON, YAML, or package.json-based (using mocha property) format

      • .mocharc.js, .mocharc.json, .mocharc.yaml or .mocharc.yml are valid "rc" file names and will be automatically loaded
      • Use --config /path/to/rc/file to specify an explicit path
      • Use --package /path/to/package.json to specify an explicit package.json to read the mocha prop from
      • Use --no-config or --no-package to completely disable loading of configuration via RC file and package.json, respectively
      • Configurations are merged as applicable using the priority list:
        1. Command-line arguments
        2. RC file
        3. package.json
        4. mocha.opts
        5. Mocha's own defaults
      • Check out these example config files
    • Node/V8 flag support in mocha executable:

      • Support all allowed node flags as supported by the running version of node (also thanks to @demurgos)
      • Support any V8 flag by prepending --v8- to the flag name
      • All flags are also supported via config files, package.json properties, or mocha.opts
      • Debug-related flags (e.g., --inspect) now imply --no-timeouts
      • Use of e.g., --debug will automatically invoke --inspect if supported by running version of node
    • Support negation of any Mocha-specific command-line flag by prepending --no- to the flag name

    • Interfaces now have descriptions when listed using --interfaces flag

    • Mocha constructor supports all options

    • --extension is now an alias for --watch-extensions and affects non-watch-mode test runs as well. For example, to run only test/*.coffee (not test/*.js), you can do mocha --require coffee-script/register --extensions coffee.

    • #3552: tap reporter is now TAP13-capable (@plroebuck & @mollstam)

    • #3535: Mocha's version can now be queried programmatically via public property Mocha.prototype.version (@plroebuck)

    • #3428: xunit reporter shows diffs (@mlucool)

    • #2529: Runner now emits a retry event when tests are retried (reporters can listen for this) (@catdad)

    • #2962, #3111: In-browser notification support; warn about missing prereqs when --growl supplied (@plroebuck)

    🐛 Fixes

    📖 Documentation

    🔩 Other

    Commits

    The new version differs by 209 commits ahead by 209, behind by 39.

    • 42303e2 Release v6.0.0
    • a553ca7 punctuation updates for changelog v6.0.0
    • c710792 grammar updates for changelog v6.0.0
    • 9f9293a update changelog for v6.0.0
    • a540eb0 remove "projects" section from MAINTAINERS.md [ci skip]
    • 52b5c42 Uppercased JSON reporter name in describe title (#3739)
    • 82307fb Fix .globals to remove falsy values (#3737)
    • 56dc28e Remove unnecessary post-processing code having no effect; closes #3708 (#3733)
    • 16b4281 Documentation updates (#3728)
    • 5d9d3eb Update nyc
    • 118c9ae Refactor out usages of Suite#_onlyTests and Suite#_onlyTests (#3689) (#3707)
    • 0dacd1f Add ability to unload files from require cache (redux) (#3726)
    • 66a52f2 update release steps [ci skip]
    • 45ae014 Refactor lookupFiles and files (#3722)
    • 94c9320 fix --reporter-option to allow comma-separated options; closes #3706

    There are 209 commits in total.

    See the full diff

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 16
  • An in-range update of @types/chai is breaking the build 🚨

    An in-range update of @types/chai is breaking the build 🚨

    The devDependency @types/chai was updated from 4.2.0 to 4.2.1.

    🚨 View failing branch.

    This version is covered by your current version range and after updating it in your project the build failed.

    @types/chai is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

    Status Details
    • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper Bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 11
  • Loosing Vue reactivity with VueX plugin set

    Loosing Vue reactivity with VueX plugin set

    I have a pretty simple app where I want to persist a few preferences. I have set VueJS-Storage as vuex plugin. I see that the localStorage does correctly reflect the state but the computed data are not updated. Disabling vuejs-storage solves the problem and everything becomes reactive again. It seems like an error would happen in the background without being reported (like in setTimeout). I also tried to import vuejs-storage/dist/vuejs-storage.js but no error is output.

    help wanted solved 
    opened by rderimay 10
  • Type error when using in typescript

    Type error when using in typescript

    In my index.ts, I have the following:

    import vuejsStorage from 'vuejs-storage';
    
    Vue.use(vuejsStorage);
    

    But the Vue.use has the following error: 'vuejsStorage' only refers to a type, but is being used as a value here.ts(2693)

    I had this issue on 3.0.1 but after upgrading to the latest, I still have the error.

    Another weird issue, might not be related. I don't know. When I run npm run serve, I get the following error! Can't find a way for typescript to not type check event if node_modules is in the excluded list

    ERROR in _____/node_modules/vuejs-storage/src/drivers.ts(3,10):
    3:10 Member 'storage' implicitly has an 'any' type.
        1 | import { StorageDriver } from './interfaces'
        2 | export default class StroageDriverImpl implements StorageDriver {
      > 3 |         private storage
          |                 ^
        4 |         constructor(storage: Storage) {
        5 |                 this.storage = storage
        6 |         }
    
    opened by paparent 6
  • Add namespaceFactory option

    Add namespaceFactory option

    This PR enables creating component-namespaced store instances like following:

    storage: {
            driver: vuejsStorage.drivers.localStorage,
            keys: ['txt'],
            namespace: '',
            namespaceFactory: function (instance) {
                return 'calculator-' + instance.calculator.id; // 'calculator' is component prop
            }
    },
    
    opened by kminek 5
  • Error with typescript when add plugin on vuex

    Error with typescript when add plugin on vuex

    I encounter this error when i try to add the plugin to my vuex store with typescript

    Property 'loggedIn' does not exist on type 'object'.
    

    here is my store.ts file:

    import Vue from "vue";
    import Vuex from "vuex";
    
    import storage from 'vuejs-storage';
    
    import axios, { AxiosRequestConfig } from "axios";
    import router from "./router";
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      state: {
        loggedIn: false,
        loginError: null,
        userName: null
      },
      
      mutations: {
        loggedIn(state, data) {
          state.loggedIn = true;
          state.userName = data.userName || "";
    
          router.push("/");
        },
    
        loggedOut(state) {
          state.loggedIn = false;
          router.push("/login");
        },
    
        loginError(state, message) {
          state.loginError = message;
        }
      },
    
      actions: {
        async login({ dispatch, commit }, data) {
          //Logout logic
              commit("loggedIn", { userName: 'UserNameFromAPI'});
        },
    
        async logout({ commit }) {
          //Logout logic
              commit("loggedOut");
        },
      },
    
      plugins: [
            storage({
    		namespace: 'namespace',
    		keys: ['loggedIn','username']
    	      })
    	],
    });
    

    The error comes out in the moment i add the storage function in the plugins array.

    Please help me figuring out what am i missing

    question 
    opened by AndreaMinato 4
  • Update karma-typescript to the latest version 🚀

    Update karma-typescript to the latest version 🚀


    ☝️ Important announcement: Greenkeeper will be saying goodbye 👋 and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


    The devDependency karma-typescript was updated from 4.1.1 to 5.0.0.

    This version is not covered by your current version range.

    If you don’t accept this pull request, your project will work just like it did before. However, you might be missing out on a bunch of new features, fixes and/or performance improvements from the dependency update.


    Publisher: erikbarke License: MIT

    Find out more about this release.


    FAQ and help

    There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


    Your Greenkeeper bot :palm_tree:

    greenkeeper 
    opened by greenkeeper[bot] 3
  • Vue 3 support?

    Vue 3 support?

    Hi, this looks like a great library, but do you plan to update it to support Vue 3?

    I'm assuming it doesn't support Vue 3 since the last release was mid 2018, and Vue 3 came out late 2020.

    opened by vincerubinetti 2
  • vuejs-storage 能设置存储到不同存储方式吗?

    vuejs-storage 能设置存储到不同存储方式吗?

    Why can't it be used like this?

    plugins: [ vuejsStorage( { namespace: "superAdmin.sessionStorage", driver: vuejsStorage.drivers.sessionStorage, keys: ["token"] }, { namespace: "superAdmin.localStorage", driver: vuejsStorage.drivers.localStorage, keys: ["user"] } ) ]

    opened by caihuattkl 1
  • Uncaught TypeError: Cannot set property 'String' of undefined

    Uncaught TypeError: Cannot set property 'String' of undefined

    2.4.0 has this bug. 2.3.3 is ok.

    image

    my store/index.ts file

    import Vue from "vue"
    import Vuex from "vuex"
    import vuejsStorage from "vuejs-storage"
    
    const getters: any = require("./getters")
    import login from "./modules/login"
    
    Vue.use(Vuex)
    
    const store = new Vuex.Store({
      getters,
      modules: {
        login
      },
      plugins: [
        vuejsStorage({
          keys: ["login"],
          namespace: "planx"
        })
      ]
    })
    
    export default store
    
    opened by transtone 8
  • Define the keys within the modules

    Define the keys within the modules

    This is not a bug. It is a request / question.

    Let say you have a standard vuex structure with a few modules

    export default new Vuex.Store({
      modules: {
        moduleA,
        moduleB,
    },
    
      plugins: [
        VueJsStorage({
          keys: [
            'moduleA.all'
          ],
          namespace: 'test',
        }),
      ],
    })
    

    with moduleA:

    const state = {
      all: {},
    }
    
    export default {
      state,
      getters,
      mutations,
      actions,
    }
    

    This works perfectly, as intended. For me thought, it breaks the modularity of the modules, as the vuex parent has to know about the name of the keys to be persisted with its submodules.

    It would be more modular if the sub modules could define their permitted keys themselves.

    Is there a way to reach this?

    Many thanks!

    enhancement 
    opened by rderimay 3
Releases(3.0.0)
  • 3.0.0(Jul 6, 2018)

    Please read README.md again to migrate to 3.0.0

    Breaking Changes

    storage,parse,stringify option removal

    FAQ

    Does it means I cannot use custom storage or parse/stringify function?

    No, you could create your own driver and use your own storage and functions.

    But why?

    Sometimes if you need to add some extra feature on default storage, which already did parsing and stringifying internally. But you forget to prevent default parse and stringify works by setting x=>x might led to double serialization. So I decided to use a driver as an abstration layer of storage to prevent this from happened. Example storage: https://github.com/maple3142/WynnStats/blob/aad20737ad6aae063c874fdf13b3c1ad37cc8f1f/src/cacheStorage.js

    Source code(tar.gz)
    Source code(zip)
  • 2.0(Mar 16, 2018)

Owner
maple
Undergraduate student from Taiwan
maple
The Vuex plugin to enable Object-Relational Mapping access to the Vuex Store.

Vuex ORM ?? HEADS UP! Currently, Vuex ORM Next project is on going, and we are hoping it is going to be the foundation of the version 1.0.0 release. W

Vuex ORM 2.4k Dec 29, 2022
Todos-VUEX - A todo list made using Vue, Vuex, Axios and JSON Placeholder API.

todos Project setup npm install Compiles and hot-reloads for development npm run serve Compiles and minifies for production npm run build Lints and

Lasanja 0 Jan 3, 2022
Enable two-way data binding for form fields saved in a Vuex store

vuex-map-fields Enable two-way data binding for form fields saved in a Vuex store. Install npm install --save vuex-map-fields Basic example The follow

Markus Oberlehner 1.4k Dec 2, 2022
Use a JSONAPI api with a Vuex store, with data restructuring/normalization.

jsonapi-vuex A module to access JSONAPI data from an API, using a Vuex store, restructured to make life easier. Vue 3 - v5 and later supports only Vue

Matthew Richardson 145 Dec 22, 2022
vuex-module-generator - It allows you to create a vuex module easily.

Vuex Module Generator (VMG) VMG allows you to create a vuex module easily. See All implementations. See Customer Example. Supported module types Clone

Abdullah 91 Dec 28, 2022
💾🔗🖥️ Share, synchronize and persist state between multiple tabs with this plugin for Vuex. TypeScript types included.

vuex-multi-tab-state This Vuex plugin allows you to sync and share the status of your Vue application across multiple tabs or windows using the local

Gabriel Martín Blázquez 155 Nov 19, 2022
A Vuex plugin to persist the store. (Fully Typescript enabled)

vuex-persist A Typescript-ready Vuex plugin that enables you to save the state of your app to a persisted storage like Cookies or localStorage. Info :

Arnav Gupta 1.6k Dec 30, 2022
Vuex plugin for redux-saga

vuex-coolstory Use redux-saga with Vuex. Overview redux-saga is an awesome library that aims to make side effects (i.e. asynchronous things like data

Nikita Lvov 23 Apr 2, 2022
vuex plugin

vuex-local-state inject localStorage to vuex Installation $ npm install vuex-local-state --save API new VuexLocalState(storeOptions, [conf]); conf def

imconfig 18 Jul 30, 2020
Bryce Soghigian 1 May 18, 2021
A project to demonstrate the use of Store and state, getters, mutations in Vuex and VueJS

Vuex State Sample ?? ?? A project to demonstrate the use of Store and state, getters, mutations in Vuex and VueJS. Create Vuex Store and use it to hol

Yufenyuy Veyeh Didier 0 Apr 13, 2020
Modular security for Vue, Vuex, Vue-Router and Nuxt

vue-kindergarten Introduction vue-kindergarten is a plugin for VueJS 2.0 that integrates kindergarten into your VueJS applications. It helps you to au

Jiří Chára 309 Dec 8, 2022
:seedling: Vue and vuex based library, writing less verbose code.

lue ?? Vue and vuex based library, writing less verbose code. Installation Install the pkg with npm: npm install lue --save or yarn yarn add lue Bas

Pomy 12 Jul 30, 2020
📦 Fast, Simple, and Lightweight State Manager for Vue 3.0 built with composition API, inspired by Vuex.

v-bucket NPM STATUS: ?? Fast, Simple, and Lightweight State Management for Vue 3.0 built with composition API, inspired by Vuex. Table of Contents Mai

mehdi 42 Aug 10, 2022
Simple counter with Vue.js and Vuex as state management

vuex-counter Project setup npm install Compiles and hot-reloads for development npm run serve Compiles and minifies for production npm run build Li

Kevin Hamdajani 0 Dec 30, 2021
💾 Persist and rehydrate your Vuex state between page reloads.

vuex-persistedstate Persist and rehydrate your Vuex state between page reloads. Install npm install --save vuex-persistedstate The UMD build is also a

Robin van der Vleuten 5.8k Jan 5, 2023
Vuex binding for client-side search with indexers and Web Workers :green_book::mag:

Vuex Search is a plugin for searching collections of objects. Search algorithms powered by js-worker-search. See working example here. Installation: n

Albert Lucianto 160 Dec 24, 2022
Vuex state persistance and synchronization between tabs/windows.

vuex-basement Vuex state persistance and synchronization between tabs/windows. Tested to work with Vue2. One Shortcomming (please read before use). Th

Rashad Saleh 65 Jun 29, 2022
:hammer: Utilities for vuex to easily create and manage actions.

vuex-action Utilities for vuex to easily create and manage actions. Allow you to create untyped action Support for Promise Work with [email protected] and [email protected] I

varHarrie 27 Mar 26, 2021