In addition to supporting general use, support for Vue data binding and even multi-page data binding and sync.
-
Support Vue2, vue3, and Vue-Cli project
-
Support Nuxt.js
-
Multi-page data binding and sync.
-
Provide storage change event listeners.
-
Various calling methods.
-
Automatic JSON parsing.
-
Support Vue2, vue3
-
Mainly written using es6 and proxy.
You can open multiple pages at the same time and experience data binding between multiple pages
npm i the-storages
// npm i the-storages
import { createLocal, createSession } from 'the-storages'
const mirror = createLocal() // create localStorage; createSession is sessionStorage
const storage = mirror._prx
console.log(storage, mirror)
storage.set('hello', 'world')
console.log(storage, mirror)
Vue-Cli: please use vue-the-storages
See index.html for details (vue3). vue2.html, vue2_zh.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- storages test page for vue2 -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>the-storages | vue2</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<h1>the-storage | vue2</h1>
<div>storageData (storage mirror object): {{ storageData }}</div>
<div>storageProxyObj (storage proxy object): {{ storageProxyObj }}</div>
<div>
<button @click="test">click me, set a message</button>
</div>
</div>
<script>
import { createLocal, createSession, createStorage } from 'the-storages'
// create storage mirror object (localStorage)
// mirror object used for data binding, get data
const mirror = createLocal()
// storage proxy object (enhanced storage)
// used to operate storage
const storage = mirror._prx
new Vue({
el: '#app',
data() {
return {
// the mirror object can make the data update automatically
// so it's more suitable for obtaining storage data
storageData: mirror,
// the storage proxy object has all the methods and features
// (but it is not recommended to put it directly into the view)
// so it's more suitable for storage operation
storage: storage
}
},
created() {
// ensure that the storage data on the view can be updated automatically
this.storage.bindVm(this)
console.log(this.storageData)
this.storage.set('hello', 'firstData')
console.log(this.storageData)
},
methods: {
test () {
this.storage.set('foo', { bar: 1 })
}
}
})
</script>
</body>
</html>
// set data to localStorage
storage.set('test', { message: 'im an object' }) // set a object
storage.setItem('test2', 'hello2') // set a string
storage.test3 = { hello111: 'im an object too' } // set a object
// set multiple data to localStorage
storage.set(['a','b','c'], [1,2,'g']) // parameter [keys ... ]:[values... ]
storage.set({a: 1, b: 2, c: 'g'}) // { key1: value1, key2: value2 ... }
// set data to localStorage, recursive creation
storage.a.b.c.d.e = 'test'
storage.setChain('aa.bb.cc.dd', 'testChain')
// each sync method has a sync copy method
storage.setAsync('async foo', 'bar').then(res => { console.log('set async complete') })
storage.setChainAsync('gg.ee.rr', 'haha').then(res => { console.log('set asyncChain complete') })
// get data from localStorage
storage.get('test') // will get object
console.log(storage.test) // the same
storage.getItem('test') // the same
localStorage.getItem('test') // the same
storage.get('test', false) // will get json string
// get multiple results
storage.get(['test', 'test2', 'test3']) // will get object { key1: value1, key2: value2 ... }
// recursive acquisition
storage.getChain('a.b.c.d.e')
storage.a.b.c.d.e
// each sync method has a sync copy method
storage.getAsync('test').then(res => { console.log(res) })
// remove key from localStorage
storage.remove('test') // none return
storage.remove('test', true) // will return test's value
storage.pop('test') // the same
// watchers
// active: events triggered by the current page
storage.watchActive('get', e => { console.log(e) })
// passive: events triggered by the other page
storage.watchPassive('set', e => { console.log(e) })
// valid events
console.log(storage._activeEvents) // active events
console.log(storage._passiveEvents) // passive events
// unwatch
storage.unwatchActive('get')
storage.unwatchPassive('get')
Some docs here...
import { createLocal, createSession, Storage } from 'the-storages'
const mirror = createLocal() // create localStorage; createSession is sessionStorage
const storage = mirror._prx // storage proxy
-
create enhanced localStorage
only localstorage supports multi-page data bindingcreateLocal(options)
Default options
{ vueModule: null, strict: true, mirrorOperation: false, updateMirror: true }
-
create enhanced sessionStorage Since the session of each page is independent, multi-page data binding is not supported
createSession(options)
Default options: same
-
get item from storage
storage.getItem(key, parse = true)
if key is an Array, get multiple, return object.
if parse, try to return JSON.parse(result)
-
Shorthand method name for getItem
storage.get(key, parse = true)
-
Asynchronous method of getItem
storage.getAsync(...args).then(res => {})
-
set item from storage
storage.setItem(key, value)
If both key and value are array types, set multiple. [...keys] -> [...values]
If key is an Object, set multiple. { key1: value1, key2: value2 }The value will fix with JSON.stringify
-
Shorthand method name for setItem
storage.set(key, value)
-
Asynchronous method of setItem
storage.setAsync(...args).then(res => {})
-
remove item from storage
storage.removeItem(key, pop = false)
If key is an Array, remove multiple keys.
If pop, removeItem will return the deleted value
-
Shorthand method name for removeItem
storage.remove(key, pop = false)
-
Asynchronous method of removeItem
storage.removeAsync(...args).then(res => {})
-
clear the storage
storage.clear()
-
Asynchronous method of clear
storage.clearAsync().then(res => {})
-
Set storage data recursively, try not to overwrite the attributes on the chain.
storage.setChain(keyChain, value)
sample: storage.setChain('a.b.c.d.e', 1) == (storage.a.b.c.d.e = 1)
Value will be set on the last object of keyChain
-
Asynchronous method of setChain
storage.setChainAsync(...args).then(res => {})
-
Get storage data recursively, will get the value of the last object on keyChain.
storage.setChain(keyChain, value)
sample: storage.getChain('a.b.c.d.e') == storage.a.b.c.d.e
Asynchronous method of getChain
storage.getChainAsync(...args).then(res => {})
-
Add a listener for the specified type of storage change event
storage.watch(triggerType, eventType, handler)
Must be 'active' or 'passive'.
active: events triggered by the current page
passive: events triggered by the other pageAdd handler function for specified event.
active: must in ["get", "set", "remove", "pop", "clear"]
passive: must in ["set", "remove", "clear"]Handler will receives a parameter: event
-
Asynchronous method of watch, triggerType is 'active'
storage.watchActive(eventType, handler)
-
Asynchronous method of watch, triggerType is 'passive'
storage.watchPassive(eventType, handler)
-
Remove listener for the specified type of storage change event
storage.unwatch(triggerType, eventType)
Must be 'active' or 'passive'.
active: events triggered by the current page
passive: events triggered by the other pageRemove listener for specified event.
active: must in ["get", "set", "remove", "pop", "clear"]
passive: must in ["set", "remove", "clear"] -
Asynchronous method of unwatch, triggerType is 'active'
storage.unwatchActive(eventType)
-
Asynchronous method of unwatch, triggerType is 'passive'
storage.unwatchPassive(eventType)
-
Binding the Vue module (instance) object to ensure that the Vue view can be updated.
storage.bindVm(vueModule)
Equivalent to "this" in the vue instance.
Please call this function to bind "this" when the page is initialized. -
return storage data as JSON string
storage.toString()
-
return storage data as Object
storage._data()
const _Storage = new Storage()
-
create and return an enhanced storage mirror object.
_Storage.create(type, options)
must be 'localStorage' or 'sessionStorage'.
Please see the default options of createLocal
-
Convert sync functions to async functions and return
_Storage._asyncWrapper(func)
sync functions
-
Create Object through Array
_Storage._asyncWrapper(list, defaultValue = null))
keys Array
every key's value
-
is val === null || undefined || nan ?
_Storage._notNull(val)
-
Try to parse the JSON string (return the original value if it fails)
_Storage._parse(value)
-
Try to stringify the value (return the original value if it fails)
_Storage._stringify(value)
-
Compress two Arrays into an object corresponding to a key value
_Storage._zip(array1, array2)
keys Array
values Array
You are willing to help me improve this project. Or you need to do some testing.
git clone https://github.com/Pure-Peace/the-storages
npm i
npm run dev
I provide two sample pages: vue.js 3 and vue.js 2 (CDN unpkg.com)
You can open two pages to experience multi-page data binding and data synchronization.
http://localhost:8080
http://localhost:8080/vue2
http://localhost:8080/vue2_zh
It is recommended to use snowpack to run or build (instead of webpack with babel, beacuse snowpack natively supports es6, and faster)