create account

前端数据库IndexedDB / 网络研习社#42 by lemooljiang

View this thread on: hive.blogpeakd.comecency.com
· @lemooljiang ·
$8.18
前端数据库IndexedDB / 网络研习社#42
![indexeddb.jpg](https://cdn.steemitimages.com/DQmR5iQyM5zVTy5stXaXKjdaH2RNntNLQ42WxFsRXGXDo2T/indexeddb.jpg)

得益于村长 @ericet 的帮助,用SteemJS可以获取到作者的全部文章了!这些文章我先是存在Vuex中的,但是这样有个坏处,就是它是基于内存的,页面一关就什么也没有,又要重新从节点中获取数据。这个重获的过程耗时耗力,能不能直接存在本地呢,这样我每次要用的话直接读取本地的数据就行啰。

刚开始是用的localStorage来存的,好像不错,测试还蛮好的。不过,用我的帐号时则直接报错了!我大约有近千篇的文章,用localStorage是不够存的。上网查了下,localStorage大约只能存5M。好吧,换别的试试。

有个Web SQL有点印象,是做前端存储的。查了下,据说很多浏览器都不支持,都转向IndexedDB了。IndexedDB是很多浏览器都支持的,与现在的前端发展相连合,非常适用,那就它吧。

好吧,我承认又是挖了一个大坑!看手册也就一个页面,但真学起来折腾得不轻。中文的大部分资料都是相互拷贝的,看起来真让人头疼,因为作者也没有实现过,都是在罗列知识点,跑起来啥情况,不知道?!

又是研究了无数的资料,测试了无数的组合,终于是入了个门,能跑起来,能用了。真心不易啊!

先来个简单的数据库初始化看看:

### 数据库初始化
第一次打开数据库时,会先触发upgradeneeded事件,然后触发success事件。
```js

initDatabase(){
  var that = this;
  var db = null;
  var openRequest;
  var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
  var dbName = 'mysteem';
  var tableName = 'posts';

  if (!indexedDB) {
    alert("你的浏览器不支持IndexedDB");
  };

  openRequest = indexedDB.open(dbName, 1); //创建或打开数据库

  //数据库创建或更新事件  创建或版本号升级时会触发,从而新建表
  openRequest.onupgradeneeded = function(event){
    console.log('数据库创建或更新');
    db = event.target.result;
    console.log(db.version, '数据库版本');
    if( !db.objectStoreNames.contains(tableName) ){ //判断表是否存在
      var objectstore = db.createObjectStore(tableName, {keyPath: 'id', autoIncrement: true}); //指定主键 id, 自增
      //新建表索引,IDBObject.createIndex()的三个参数分别为索引名称、索引所在的属性、配置对象(说明该属性是否包含重复的值)。
      objectstore.createIndex('title', 'title', {unique: false});
    }
  };

  //数据库打开成功(如果数据库已经存在)
  openRequest.onsuccess = function(event) {
    db = event.target.result;
    console.log(666, db, '版本号', db.version);
    db.onerror = function (event) {
      //针对此数据库的所有错误的通用错误处理程序
      alert("Database error:" + event.target.errorCode);
      console.dir(event.target);
    };
    that.db = db;  //挂载到全局中
  };

  //数据库打开错误
  openRequest.onerror = function(event){
    console.log(event, '数据库打开错误')
  };

},
```

单是这个数据库创建就折腾了快一天了,怎么试都不行,好在最后解决了。IndexedDB是由浏览器打开创建,相当轻量,而且几个浏览器(chrome, firefox, opera)我都试了下,都可以用!IndexedDB是基于事件驱动的,有点类拟小型的MongoDB。它不同于localStorage有容量的限制,理论上是可以存一些大数据的(至少几百M是有的)。在前端应用越加广泛的今天,IndexedDB的应用场景会更多的,比如我现在就特别想把文章都存在本地,不再想看steemit网站动不动就在那里转圈圈啊。

**IndexedDB的优点是有无数多的!**入门和应用也不难,你会点对象的概念就可以了,因为它是一个个对象存进去的,所以有很多先天的优势。不过,今天在使用查询的时候,用索引的方法好像没办法使用关键字来查询,不知是没有这个方法,还是我没有看到。

用IndexedDB来存数据真会让网站飞起来,尤其是对steemit! 好了,用起来吧。
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
👎  
properties (23)
authorlemooljiang
permlinkindexeddb-42
categorycn
json_metadata{"tags":["cn","network-institute","steemjs","steemdev","indexeddb"],"users":["ericet"],"image":["https://cdn.steemitimages.com/DQmR5iQyM5zVTy5stXaXKjdaH2RNntNLQ42WxFsRXGXDo2T/indexeddb.jpg"],"app":"steemit/0.1","format":"markdown"}
created2019-10-19 12:56:00
last_update2019-10-19 12:56:00
depth0
children4
last_payout2019-10-26 12:56:00
cashout_time1969-12-31 23:59:59
total_payout_value4.137 HBD
curator_payout_value4.041 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length2,407
author_reputation440,584,497,799,091
root_title"前端数据库IndexedDB / 网络研习社#42"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id91,704,659
net_rshares27,043,798,840,220
author_curate_reward""
vote details (47)
@dailychina ·
$0.05
!thumbup
  恭喜你!您的这篇文章入选 @justyy 今日 (2019-10-21) 榜单 [【优秀的文章】](https://steemit.com/cn/@justyy/--daily-cn-updates-cncnpower-downyy2019-10-21), 回复本条评论24小时内领赏,点赞本评论将支持 @dailychina 并增加将来您的奖赏。
 @justyy 是CN区的见证人,[请支持他,给他投票](https://steemconnect.com/sign/account_witness_vote?approve=1&witness=justyy),或者设置justyy为[见证人代理](https://v2.steemconnect.com/sign/account-witness-proxy?proxy=justyy&approve=1)。感谢!@justyy的主要贡献:https://steemyy.com

Congratulations! This post has been selected by @justyy as today's (2019-10-21)  [【Good Posts】](https://steemit.com/cn/@justyy/--daily-cn-updates-cncnpower-downyy2019-10-21), Steem On!  Reply to this message in 24 hours to get rewards. Upvote this comment to support the @dailychina and increase your future rewards! ^_^

[SteemIt 工具、API接口、机器人和教程](https://steemyy.com/steemit-tools/)
[SteemIt Tools, Bots, APIs and Tutorial](https://SteemYY.com)<hr>
If you believe what I am doing, please consider a spare vote voting me [here](https://steemconnect.com/sign/account_witness_vote?approve=1&witness=justyy), thank you very much indeed.

@justyy - the author of https://SteemYY.com and I have been a Steem Witness for [more than a year now.](https://steemit.com/witness-category/@justyy/one-year-winessversary-a-great-start)
👍  , , , , , , , , , , , ,
properties (23)
authordailychina
permlinkre-indexeddb-42-20191021t080130
categorycn
json_metadata""
created2019-10-21 08:01:30
last_update2019-10-21 08:01:30
depth1
children0
last_payout2019-10-28 08:01:30
cashout_time1969-12-31 23:59:59
total_payout_value0.023 HBD
curator_payout_value0.022 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,249
author_reputation50,124,640,567,504
root_title"前端数据库IndexedDB / 网络研习社#42"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id91,760,231
net_rshares259,412,845,347
author_curate_reward""
vote details (13)
@digitalboss ·
Is this android html app
👍  
properties (23)
authordigitalboss
permlinkpzmsn1
categorycn
json_metadata{"app":"steemit/0.1"}
created2019-10-19 17:01:48
last_update2019-10-19 17:01:48
depth1
children0
last_payout2019-10-26 17:01:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length24
author_reputation-2,119,721,877,154
root_title"前端数据库IndexedDB / 网络研习社#42"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id91,710,594
net_rshares0
author_curate_reward""
vote details (1)
@miti ·
@tipu curate
properties (22)
authormiti
permlinkpzmhga
categorycn
json_metadata{"users":["tipu"],"app":"steemit/0.1"}
created2019-10-19 13:00:12
last_update2019-10-19 13:00:12
depth1
children1
last_payout2019-10-26 13:00:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length12
author_reputation435,902,954,694,677
root_title"前端数据库IndexedDB / 网络研习社#42"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id91,704,749
net_rshares0
@tipu ·
<a href="https://tipu.online/curator?miti" target="_blank">Upvoted &#128076;</a> (Mana: 33/37)
properties (22)
authortipu
permlinkre-pzmhga-20191019t130043
categorycn
json_metadata""
created2019-10-19 13:00:45
last_update2019-10-19 13:00:45
depth2
children0
last_payout2019-10-26 13:00:45
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length94
author_reputation55,955,193,176,147
root_title"前端数据库IndexedDB / 网络研习社#42"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id91,704,765
net_rshares0