localforage,好用的indexedDB插件,可以本地存储大数据

文章介绍了如何使用localforage这一库来简化对indexedDB的复杂API操作,它提供了一种更简洁的接口,类似于localStorage和sessionStorage。当需要存储超过4MB的大数据,如3D数据、geojson或图片时,localforage是一个理想选择。通过示例展示了利用localforage进行数据读取和存储的promise语法,以提高页面加载效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

indexedDB的api地址

https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API/Using_IndexedDB

localforage中文网

https://localforage.docschina.org/

原生的indexedDB的api还是比较复杂的,localforage重新封装了一下indexedDB,使用起来更加简洁,如果有用过localstorage和sessionstorage的同学,这个用法是差不多的

不过localstorage和sessionstorage最多只能存储4M的数据,如果有大型的3D数据,或者大量的geojson数据,图片数据什么的,可以存储在localforage里面,理论上这个本地数据库的内存是和自己电脑磁盘有关系的,可以放很多数据。

就不需要每次打开页面都请求这个大数据了,第一次打开页面请求一下,然后存到localforage里面,以后再次打开就先判断localforage里面有没有,有的话,直接拿这里面的,没有的话再请求数据,可以节省大量的请求时间。

使用起来也很方便

# 通过 npm 安装:
npm install localforage


import localforage from 'localforage'

然后使用的时候有回调和promise两种写法,我这里展示一下promise的写法,和localstorage、sessionstorage用法是一样的,就是后面加上了一个.then 和.catch

      localforage.getItem('gridGeojson').then(function(value) {
          if(value){
            self.gridGeojson = value
            self.fullScreenLoading.close()
          }else{
            self.$axios({
                  url:geoserverUrl+geoserverGeojsonHeader+'result'+geoserverGeojsonEnd,
                  cache: false,
                  async: true,
            }).then(res=>{
              localforage.setItem('gridGeojson', res.data).then(function (value) {
                self.gridGeojson = value
              }).catch(function(err) {
                  console.log(err);
              });
              self.fullScreenLoading.close()
            });
          }
      }).catch(function(err) {
          // 当出错时,此处代码运行
          console.log(err);
      });
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值