weekly
weekly copied to clipboard
【开源自荐】一个js库,用proxy封装了localStorage、sessionStorage
项目地址: https://github.com/KID-joker/proxy-web-storage 文章地址: https://juejin.cn/post/7144142689594769415 项目介绍: 借助proxy,扩展了web storage的功能,使用起来,更加方便快捷,也更加强大。主要功能为保持值类型不变,可直接操控Object、Array,支持监听数据变化和设置过期时间。
Features
Base
Get what you set and change array and object directly.
import { local, session } from 'proxy-web-storage';
local.test = 'Hello proxy-web-storage'; // works
delete local.test; // works
// number
local.test = 0;
local.test === 0; // true
// boolean
local.test = false;
local.test === false; // true
// undefined
local.test = undefined;
local.test === undefined; // true
// null
local.test = null;
local.test === null; // true
// object
local.test = { hello: 'world' };
local.test.hello = 'proxy-web-storage'; // works
// array
local.test = ['hello'];
local.test.push('proxy-web-storage'); // works
local.test.length // 2
// Date
local.test = new Date('2000-01-01T00:00:00.000Z');
local.test.getTime() === 946684800000; // true
// RegExp
local.test = /d(b+)d/g;
local.test.test("cdbbdbsbz"); // true
// function
local.test = function() {
return 'Hello proxy-web-storage!';
};
local.test() === 'Hello proxy-web-storage!'; // true
Subscribe
listen for changes.
import { local } from 'proxy-web-storage';
local.on('test', function(newVal, oldVal) {
console.log('test', newVal, oldVal);
});
local.on('test.a', function(newVal, oldVal) {
console.log('test.a', newVal, oldVal);
});
local.test = {};
// test {} undefined
local.test.a = 1;
// test.a 1 undefined
Expired
set expires for items.
import { local } from 'proxy-web-storage';
local.test = 'hello proxy-web-storage';
local.setExpires('test', Date.now() + 10000);
// after 10's
local.test // undefined
谢谢阮老师的推荐!