简单封装localStorage和sessionStorage

栏目: Html5 · 发布时间: 6年前

内容简介:由于项目中常需用到本地storage存储,复杂的数组、对象等,每次都需要1、安装2、使用

由于项目中常需用到本地storage存储,复杂的数组、对象等,每次都需要 JSON.stringify()JSON.parse() 进行序列化、反序列化操作,觉得有点麻烦,再者,存入storage的数值,取出来就变成字符串了,因此,对storage简单封装了一下,使取出的值类型和存入时保持一致,也可以存入整个object对象。

1、安装

npm install pz_storage --save
复制代码

2、使用

import storage from 'pz_storage';

// 存储单个值
storage.set('name', 'esther');
// 获取单个值
storage.get('name');
// 删除单个值
storage.remove('name');
// 清空全部
storage.clear();
// 存储对象,key - value形式
storage.setList({
   a: '1',
   b: '2.1',
   c: ['a', 'b', 'c'],
   d: {
      'd-1': 'd-1',
      'd-2': 'd-2'
   },
   e: true,
   f: new Date(),
   g: function(){
      console.log(111);
   }
});
// 获取多个值,传入数组形式的key
storage.getList(['a', 'b', 'd', 'f']);
// 删除多个值,传入数组形式的key
storage.removeList(['a', 'b', 'd', 'f'])

// sessionStorage, api同上
storage.session.set('name', 'esther');
复制代码

也可直接在HTML页面引入dist文件夹下的storage.js

<script src="dist/storage.js"></script>
复制代码

github地址


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Lighttpd

Lighttpd

Andre Bogus / Packt Publishing / 2008-10 / 39.99

This is your fast guide to getting started and getting inside the Lighttpd web server. Written from a developer's perspective, this book helps you understand Lighttpd, and get it set up as securely an......一起来看看 《Lighttpd》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具