Git Product home page Git Product logo

vuejs-storage's Introduction

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

vuejs-storage's People

Contributors

fossabot avatar greenkeeper[bot] avatar kerasus avatar kouts avatar maple3142 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

vuejs-storage's Issues

Feature suggestion

Hi i think it would be nice to have the chance to save some states in sessionStorage and some in localStorage similar to this:

plugins: [
  vuejsStorage({
    namespace: 'multistorage',
    localStorageKeys: ['keyA', 'keyB'], //keys to be saved in localStorage
    sessionStorageKeys: ['keyC'],  //keys to be saved in sessionStorage 
  })
]

until now i can make it work like that:

plugins: [
    vuejsStorage({
      namespace: "storage_session",
      storage: window.sessionStorage, //keys to be saved in sessionStorage 
      keys: ["keyC"], 

    }),
    vuejsStorage({
      namespace: "storage_local",
      keys: ["keyA", "keyB"] //keys to be saved in localStorage
    })
  ]

so it works if i declare two plugin one with sessionStorage and one with localStorage and using two different namespace. i don't know what will be the behaviour if i use the same namespace and if i use the same key in both the plugins.

do you think taht this would be possible and that it makes sense?
In my opinion it would boost your library making tha api far more easy to use .

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 |         }

3.0 Roadmap

API Change

3.0 option structure:

interface StorageDriver {
  set: (key: string,value: any)=>void
  get: (key: string)=>any
  has: (key: string)=>boolean
}
interface Option {
  keys: string[]
  namespace: string
  merge: (obj1: object,...object)=>object //default=internal merge function
  driver: StorageDriver //default=localStorageDriver
}

Builtin Driver for localStorage & sessionStorage

Maybe in vuejsStorage.localStorageDriver & vuejsStorage.sessionStorageDriver

Module not found: Error: Can't resolve 'vuejs-storage' in ...

VueJS Storage started to fail some hours ago, after 3.0.2 commit.

When doing an asset-prod it outputs:

 ERROR  Failed to compile with 1 errors                                              1:40:47

This dependency was not found:

* vuejs-storage in ./node_modules/@xxx/mm-component-lib/src/install.js

To install it, you can run: npm install --save vuejs-storage
 4 assets

ERROR in ./node_modules/@xxx/mm-component-lib/src/install.js
Module not found: Error: Can't resolve 'vuejs-storage' in '...'
 @ ./node_modules/@xxx/mm-component-lib/src/install.js 32:0-41 131:12-24
 @ ./node_modules/@xxx/mm-component-lib/index.js
 @ ./resources/js/app.js
 @ multi ./resources/js/app.js ./resources/sass/app.scss
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] asset-production: `cross-env NODE_ENV=production node_modules/
webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/
webpack.config.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] asset-production script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output
above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\xxx\AppData\Roaming\npm-cache\_logs\2020-08-25T23_40_47_576Z-debug.
log
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Process finished with exit code 2

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!

typescript type error

➜  ~ node -v
v16.2.0

package.json

    "vue": "^2.6.11",
    "vuejs-storage": "^3.1.0",
    "vuex": "^3.4.0",
    "typescript": "~4.1.5",

store/index.ts

import Vue from 'vue'

import Vuex from 'vuex'
Vue.use(Vuex)

import vuejsStorage from 'vuejs-storage'

export default new Vuex.Store({
  state: {
    count: 0,
  },
  plugins: [
    vuejsStorage({
      keys: ['state'],
      namespace: 'storage',
      driver: vuejsStorage.drivers.sessionStorage,
    }),
  ],
})

image

11:21 Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.
     9 | 	}
    10 | 	get(key: string) {
  > 11 | 		return JSON.parse(this.storage.getItem(key))
       | 		                  ^
    12 | 	}
    13 | 	has(key: string) {
    14 | 		return !!this.storage.getItem(key)

ERROR in /home/puzzle/vhost/web/eaten/wap/src/store/index.ts(13,18):
13:18 Expected 0 arguments, but got 1.
    11 |   },
    12 |   plugins: [
  > 13 |     vuejsStorage({
       |                  ^
    14 |       keys: ['state'],
    15 |       namespace: 'storage',
    16 |       driver: vuejsStorage.drivers.sessionStorage,

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.

vuejs-storage is not working

image

The value has been assigned to the store. But after the refresh, the data is lost! vuejs-storage is not working

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"]
}
)
]

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


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 🌴

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

An in-range update of karma-typescript is breaking the build 🚨

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

🚨 View failing branch.

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

karma-typescript 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).

Release Notes for v4.1.1

Changes

Bugfixes

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 🌴

typescript error of vuejs-storage.d.ts

ERROR in /myapp/node_modules/vuejs-storage/types/vuejs-storage.d.ts
17:48 Generic type 'Plugin' requires 1 type argument(s).
    15 | export = vuejsStorage
    16 |
  > 17 | declare function vuejsStorage(option: Option): VuexPlugin
       |                                                ^
    18 | declare namespace vuejsStorage {
    19 | 	function install(Vue: Vue): void
    20 | }

the last commit solve the problem. please update the npm version.

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.

An in-range update of karma is breaking the build 🚨

The devDependency karma was updated from 3.1.1 to 3.1.2.

🚨 View failing branch.

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

karma 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 failed (Details).

Release Notes for v3.1.2

Bug Fixes

Features

Commits

The new version differs by 11 commits.

  • 7d4d347 chore: release v3.1.2
  • 5077c18 chore: update contributors
  • fb05fb1 fix(server): use flatted for json.stringify (#3220)
  • 2682bff feat(docs): callout the key debug strategies. (#3219)
  • 4e87902 fix(changelog): remove release which does not exist (#3214)
  • 30ff73b fix(browser): report errors to console during singleRun=false (#3209)
  • 5334d1a fix(file-list): do not preprocess up-to-date files (#3196)
  • dc5f5de fix(deps): upgrade sinon-chai 2.x -> 3.x (#3207)
  • d38f344 fix(package): bump lodash version (#3203)
  • ffb41f9 refactor(browser): log state transitions in debug (#3202)
  • 240209f fix(dep): Bump useragent to fix HeadlessChrome version (#3201)

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 🌴

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

Can't set namespace from data variable or this.$route.path

In Grid.vue:

  storage: {
    keys: ['layout', 'grid_settings'],
    namespace: this.$route.path
  },

cause error:

Grid.vue?56a8:122 Uncaught TypeError: Cannot read property '$route' of undefined
    at eval (Grid.vue?56a8:122)
    at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/vuetify-loader/lib/loader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Grid/Grid.vue?vue&type=script&lang=js& (app.js:947)
    at __webpack_require__ (app.js:786)
    at fn (app.js:151)
    at eval (Grid.vue?cae2:1)
    at Module../src/components/Grid/Grid.vue?vue&type=script&lang=js& (app.js:1600)
    at __webpack_require__ (app.js:786)
    at fn (app.js:151)
    at eval (Grid.vue?5e42:1)
    at Module../src/components/Grid/Grid.vue (app.js:1588)

How get set namespace dynamically by routing path?

I also tried to use variable from data, doesn't work.

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 🌴

"TypeError: Cannot read property 'call' of undefined"

Could you check this?, I've get below error, when I test your library in webpack based vuejs App.

[Vue warn]: Error in callback for watcher "count": "TypeError: Cannot read property 'call' of undefined"

found in

---> at src/components/Test.vue
at src/App.vue

TypeError: Cannot read property 'call' of undefined
at VueComponent.this_1.$options.watch.(anonymous function) (webpack-internal:///125:157:33)
at Watcher.run (webpack-internal:///2:3201:19)
at flushSchedulerQueue (webpack-internal:///2:2949:13)
at Array.eval (webpack-internal:///2:1808:12)
at MessagePort.flushCallbacks (webpack-internal:///2:1729:14)

[main.js]
import vuejsStorage from 'vuejs-storage'
Vue.use(vuejsStorage)

[Test.vue]

{{ count }} Add
<script> import { QBtn } from 'quasar' export default { components: { QBtn }, data () { var data = {} return data }, storage: { data: { count: 0 }, storage: sessionStorage, namespace: 'my-namespace' }, methods: { add () { this.count++ } }, computed: { } } </script>

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.