首页 > 其他分享 >typescript封装LocalStorage并支持过期时间

typescript封装LocalStorage并支持过期时间

时间:2023-01-17 14:36:01浏览次数:37  
标签:typescript 封装 过期 Dictionaries value expire LocalStorage key export


typescript封装LocalStorage并支持过期时间_Storage

思考

在我们使用​​cookie​​​的时候是可以设置有效期的,但是​​localStorage​​​本身是没有该机制的,只能人为的手动删除,否则会一直存放在浏览器当中,可不可以跟cookie一样设置一个有效期。如果一直存放在浏览器又感觉有点浪费,那我们可以把​​localStorage​​进行二次封装实现该方案。

实现思路

在存储的时候设置一个过期时间,并且存储的数据进行格式化方便统一校验,在读取的时候获取当前时间进行判断是否过期,如果过期进行删除即可。

代码实现

目录结构

typescript封装LocalStorage并支持过期时间_Storage_02

enum ts 定义枚举

//字典 Dictionaries    expire过期时间key    permanent永久不过期
export enum Dictionaries {
expire = '__expire__',
permanent = 'permanent'
}
复制代码

type ts 定义类型

import { Dictionaries } from "../enum"
export type Key = string //key类型
export type expire = Dictionaries.permanent | number //有效期类型
export interface Data<T> { //格式化data类型
value: T
[Dictionaries.expire]: Dictionaries.expire | number
}
export interface Result<T> { //返回值类型
message: string,
value: T | null
}
export interface StorageCls { //class方法约束
set: <T>(key: Key, value: T, expire: expire) => void
get: <T>(key: Key) => Result<T | null>
remove: (key: Key) => void
clear: () => void
}
复制代码

index.ts 主要逻辑实现

import { StorageCls, Key, expire, Data,Result } from "./type";
import { Dictionaries } from "./enum";
export class Storage implements StorageCls {
//存储接受 key value 和过期时间 默认永久
public set<T = any>(key: Key, value: T, expire: expire = Dictionaries.permanent) {
//格式化数据
const data = {
value,
[Dictionaries.expire]: expire
}
//存进去
localStorage.setItem(key, JSON.stringify(data))
}

public get<T = any>(key: Key):Result<T | null> {
const value = localStorage.getItem(key)
//读出来的数据是否有效
if (value) {
const obj: Data<T> = JSON.parse(value)
const now = new Date().getTime()
//有效并且是数组类型 并且过期了 进行删除和提示
if (typeof obj[Dictionaries.expire] == 'number' && obj[Dictionaries.expire] < now) {
this.remove(key)
return {
message:`您的${key}已过期`,
value:null
}
}else{
//否则成功返回
return {
message:"成功读取",
value:obj.value
}
}
} else {
//否则key值无效
console.warn('key值无效')
return {
message:`key值无效`,
value:null
}
}
}
//删除某一项
public remove(key:Key) {
localStorage.removeItem(key)
}
//清空所有值
public clear() {
localStorage.clear()
}
}

复制代码

rollup.js ​​简易打包暂时没有写的很复杂​​ 所用到的依赖 rollup rollup-plugin-typescript2 typescript

import ts from 'rollup-plugin-typescript2'
import path from 'path'
export default {
input:'./src/index.ts',
output:{
file:path.resolve(__dirname,'./dist/index.js')
},
plugins:[
ts()
]
}
复制代码

代码测试

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<script type="module">
import { Storage } from './dist/index.js'
const sl = new Storage()
//五秒后过期
sl.set('a', 123, new Date().getTime() + 5000)

setInterval(() => {
const a = sl.get('a')
console.log(a)
},500)
</script>
</body>

</html>
复制代码

测试五秒后过期增加计时器观察值

过期之后 成功删除 测试成功

typescript封装LocalStorage并支持过期时间_typescript_03

标签:typescript,封装,过期,Dictionaries,value,expire,LocalStorage,key,export
From: https://blog.51cto.com/u_13463935/6017252

相关文章

  • 学习TypeScript 加餐环节
    ​​object​​​、​​Object​​​ 以及​​{}这三个类型大家可能不太理解​​1.​​Object​​ ​​Object​​​类型是所有​​Object​​类的实例的类型。由以下......
  • 面向对象三大特性之——封装
    面向对象三大特性之——封装一、引言此篇文章来自一个初学Java不久的学生,内容的用词、深度、广度甚至部分理解不够到位,再加上Markdown语法的不熟练,所以排版不够美观。......
  • Vue 使用localStorage报错:_LocalStorage2.default.getItem is not a function
    问题在mounted中使用localStorage获取数据,没想到报错如下:打断点看过localStorage中存在getItem()方法。这个问题类似之前遇到的canvas2image的那个问题(canvasToImage报......
  • vue select 组件封装及调用
    子组件 mySelect.vue<template><divclass="mySelect"><el-selectv-model="value1"placeholder="请选择"@change="handleSelect"><el-option......
  • 重载重写、封装继承多态、String、==和equlas、Integer
    (1)重载和重写的区别:1.重载:方法名相同,参数类型、个数、顺序不同,返回值、访问修饰符可以不同;发生在编译时;2.重写:方法名、参数列表必须相同;返回值、异常范围小于等于父类,访问修......
  • vue iframe组件封装
    界面内嵌iframe时,由空白节点引起底边间距,可设置iframe属性vertical-align:top解决<template><divv-loading="loading":style="'height:'+height"><iframe......
  • React Tree树形结构封装工具类
    需要依赖 immutable,用于groupby分组buildTree为入口方法,注意返回的是Immutable.List对象,使用需要调用.toJS()方法转为普通对象其中 creatNode方法为构建节点对象,可根......
  • Linux服务管理,给JAR包封装为Linux服务
    操作服务的命令在Linux中管理服务,需要使用systemctl命令,例如常用的打开/关闭防火墙$systemctlstartfirewalld$systemctlstopfirewalld在这里列举一下systemctl......
  • vue 封装密码输入框(屏蔽浏览器反显,禁止粘贴)
    vue封装密码输入框(屏蔽浏览器反显,禁止粘贴) 备注:使用了ant-design-vue,可以换其他组件输入框或原生<template><a-inputstyle="ime-mode:disabled":valu......
  • 利用函数封装冒泡顺序
    利用函数封装冒泡顺序sort函数实现过程functionsort(arr){​for(vari=0;i<arr.length-1;i++){​for(varj=0;j<arr.length-i-1......