可以使用 storage-timing 可以设置 localStorage 定时删除。
安装
npm install --save storage-timing
使用
import { Store } from "storage-timing";
const store = new Store();
const data = store.atom("token"); // 获取键为 "token" 的数据
data.set("token 123123", Date.now() + 10 * 1000); // 设置 token 的值,同时设置它在 10 秒钟后过期
console.log(data.get()); // 获取到 "token 123123" ,10 秒钟内获取数据都可以拿到,刷新页面也行,数据存到了 localStorage 中
setTimeout(() => {
console.log(data.get()); // null ,第 11 秒钟后数据就过期了,获取到 null
}, 11 * 1000);
使用 cdn
<!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>test</title>
<script
src="https://cdn.jsdelivr.net/npm/storage-timing@1.0.6/lib/index.umd.min.js"
integrity="sha256-e4RNAWBIatQaFq51XreDnL5ZVgKMRwttV3Ka6gCsJCU="
crossorigin="anonymous"
></script>
</head>
<body>
<script>
const store = new window.StorageTiming.Store();
const data = store.atom("token"); // 获取键为 "token" 的数据
data.set("token 123123", Date.now() + 10 * 1000); // 设置 token 的值,同时设置它在 10 秒钟后过期
console.log(data.get()); // 获取到 "token 123123" ,10 秒钟内获取数据都可以拿到,刷新页面也行,数据存到了 localStorage 中
setTimeout(() => {
console.log(data.get()); // null ,第 11 秒钟后数据就过期了,获取到 null
}, 11 * 1000);
</script>
</body>
</html>