- 四个都是浏览器做数据缓存的
- 区别
存储方式 cookies sessionStorage localStorage indexDB 存储大小 4K 5M 5M 无限制 与后端联系 后端返回,在返回请求头部 无 无 无 生命周期 后端可以设置过期时间 浏览器关闭失效 手动释放 手动释放 -
使用
-
cookies
-
session cookie 没有设置失效时间,浏览器关闭cookie就会失效
-
thrid-party cookie 设置失效时间expires .ie出于安全考虑,不允许 img,iframe, link, script等标签中发送第三方cookie,火狐允许发送
-
-
sessionStorage
// 赋值 let student1 = {id: '2013010818', name: 'wangyakun', sex: 'woman', age: 20} sessionStorage.setItem('student', student1) // 取值 sessionStorage.getItem('student') // 删除 sessionStorage.removeItem('student')
-
localStorage
// 赋值 let student1 = {id: '2013010818', name: 'wangyakun', sex: 'woman', age: 20} loaclStorage.setItem('student', student1) // 取值 loaclStorage.getItem('student') // 删除 loaclStorage.removeItem('student')
- indexDB 是浏览器使用的一个本地存储,可以异步存储各种类型数据,由于需要各种监听,操作复杂,所以使用依赖库indexDBwrapper,方便了开发使用
// 安装依赖库 npm install indexdbwrapper // 引入 依赖 import IndexDBWrapper form 'indexdbwrapper' // 使用 // 创建一个实例 const indexDb = new IndexDBWrapper(name, version, {onupgradeneeded }) /* name: 数据库名 version:数据库版本 onupgradeneeded:数据库更新方法*/ // 属性 indexDb.db //db实际的 IndexDB IDBDatabase 对象。 // 方法 indexDb.open();// 打开数据库 indexDb.close();// 关闭数据库 indexDb.add(storeName, value,key)// 添加数据 indexDb.clear(storeName)// 清空指定的store的数据 indexDb.count(storeName)// 获取指定store的数据 indexDb.get(key)// 指定 store 和主键获取数据 indexDb.put(storeName, value, key?)// 指定 store 添加或更新数据 indexDb.delete(storeName, key)// 指定 store 和 key 删除符合条件的数据 indexDb.getKey(storeName, query)// 获取符合条件的 key indexDb.getAll(storeName, query, count)// 获取符合条件的所有数据 indexDb.getAllKeys(storeName, query, count)//获取符合条件的所有 key indexDb.getAllMatching(storeName, { index, query = null, direction = "next", count, includeKeys })// 获取符合条件的所有数据 indexDb.transaction(storeNames, type, callback)// 包装后的事务
-
cookies,sessionStorage , localStorage和 indexDB 的区别
最新推荐文章于 2024-04-07 23:30:24 发布