vue工具之封装LocalStorage、SessionStorage、Cookie、IndexDB 存储
一、创建文件
-
js
-
ts
二、封装
JS
⏰ localStorage:提供了一种方式来存储键值对,数据会永久保存,直到主动删除或用户清除浏览器缓存。
/** *【window.localStorage 浏览器永久缓存】 **/ export class LocalUtil { // 设置永久缓存 static set(key, value, express) { localStorage.setItem(key, JSON.stringify({ data: value, cTime: Date.now(), express: express })); } // 获取永久缓存 static get(key) { let item = localStorage.getItem(key); if (!item) { return null; } item = JSON.parse(item); let nowTime = Date.now(); if (item.express && item.express < (nowTime - item.cTime)) { LocalUtil.remove(key); return null; } else { return item.data; } } // 移除永久缓存 static remove(key) { localStorage.removeItem(key); } // 移除全部永久缓存 static clearAll() { localStorage.clear(); } }
⏰ sessionStorage:与 localStorage 类似,但其存储的数据只在页面会话期间有效(即浏览器窗口关闭时数据会被清除)。
/** *【window.sessionStorage 浏览器临时缓存】 **/ export class SessionUtil { // 设置临时缓存 static set(key, value) { window.sessionStorage.setItem(key, JSON.stringify(value)); } // 获取临时缓存 static get(key) { let json = window.sessionStorage.getItem(key); return JSON.parse(json); } // 移除临时缓存 static remove(key) { window.sessionStorage.removeItem(key); } // 移除全部临时缓存 static clearAll() { window.sessionStorage.clear(); } }
⏰ cookie:Cookie实质上是浏览器中的一小段文本文件,附加在HTTP请求中,在浏览器和服务器之间传递。它能携带用户信息,当服务器检查Cookie时,就能获取客户端的状态。然而,Cookie的主要职责并非本地存储,而是维持状态的重要角色.
/** * 【 Cookie 】 **/ export class CookieUtil { // 设置对应的Cookie值 static set(key, value, expires, path, domain, secure) { let cookieText = `${key}=${value}`; if (expires instanceof Date) { cookieText += `; expire=${expires.toGMTString()}`; } if (path) { cookieText += `; path=${path}`; } if (domain) { cookieText += `; domain=${domain}`; } if (secure) { cookieText += `; secure`; } document.cookie = cookieText; } // 获取Cookie中的对应属性 static get(key) { const cookies = document.cookie; const cookiesArr = cookies.split(';'); for (let index = 0; index < cookiesArr.length; index++) { const presentCookieArr = cookiesArr[index].split('='); if (presentCookieArr[0] === key) { return presentCookieArr[1]; } } return null; } // 删除对应的Cookie static remove(key) { CookieUtil.set(key, '', new Date(0)); } }
⏰ IndexDB:(索引数据库)是浏览器提供的一种客户端数据库,用于存储大量的结构化数据。它在浏览器中提供了一种持久性存储数据的方式,可以在离线状态下进行读写操作,并提供了强大的索引和事务支持。
/** *【IndexDB 索引数据库】 **/ class IndexedDB { // 构造器 constructor(databaseName, databaseTableName) { this.isIndexedDB = true; window.myIndexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; this.isIndexedDB = Boolean(window.myIndexedDB); if (this.isIndexedDB) { this.db = null; this.version = 1; this.databaseName = databaseName; this.databaseTableName = databaseTableName; this.dbRequest = window.myIndexedDB.open(this.databaseName, 1); this.dbRequest.onerror = (event) => { console.log("error", event); }; this.dbRequest.onupgradeneeded = (event) => { this.db = event.target.result; this.store = this.db.createObjectStore(this.databaseTableName, { keyPath: "id", }); }; } } // 初始化数据库 init() { return new Promise((resolve, reject) => { this.dbRequest = window.myIndexedDB.open(this.databaseName, this.version); this.dbRequest.onsuccess = (event) => { const db = event.target.result; if (db.objectStoreNames.contains(this.databaseTableName)) { const transaction = db.transaction( [this.databaseTableName], "readwrite" ); const objectStore = transaction.objectStore(this.databaseTableName); resolve(objectStore); } else { this.db.createObjectStore(this.databaseTableName, { keyPath: "id" }); } }; this.dbRequest.onerror = (event) => { reject(event); }; }); } // 获取对应的永久缓存 get(key) { return new Promise((resolve, reject) => { this.init().then((objectStore) => { const selectObjectStore = objectStore.get(key); selectObjectStore.onsuccess = function () { resolve(selectObjectStore.result); }; selectObjectStore.onerror = function () { console.log("查询数据失败"); reject(selectObjectStore.result); }; }); }); } // 获取所有永久缓存数据 getAll() { return new Promise((resolve, reject) => { this.init().then((objectStore) => { const results = []; const cursorObjectStore = objectStore.openCursor(); cursorObjectStore.onsuccess = function (event) { const cursor = event.target.result; if (cursor) { results.push(cursor.value); cursor.continue(); } else { resolve(results); } }; cursorObjectStore.onerror = function () { console.log("查询游标失败"); reject(cursorObjectStore.result); }; }); }); } // 设置对应的永久缓存 set(options) { return new Promise((resolve, reject) => { this.init().then((objectStore) => { const insertObjectStore = objectStore.add(options); insertObjectStore.onsuccess = function (event) { resolve(insertObjectStore.result); }; insertObjectStore.onerror = function () { console.log("插入数据失败"); reject(insertObjectStore.result); }; }); }); } // 移除对应的缓存 remove(key) { return new Promise((resolve, reject) => { this.init().then((objectStore) => { const clearRequest = objectStore.delete(key); clearRequest.onsuccess = function () { resolve("删除数据成功"); }; clearRequest.onerror = function () { console.log("删除数据失败"); reject(clearRequest.result); }; }); }); } // 移除所有的缓存 clearAll() { return new Promise((resolve, reject) => { this.init().then((objectStore) => { const clearRequest = objectStore.clear(); clearRequest.onsuccess = function () { resolve("删除数据成功"); }; clearRequest.onerror = function () { console.log("删除数据失败"); reject(clearRequest.result); }; }); }); } } export function createIndexedDB(databaseName, databaseTableName) { return new IndexedDB(databaseName, databaseTableName) }
TS
Storeage: https://github.com/DisneyTom/storage.git