简介
indexedDB
1.前端浏览器本地基于javascript的事务性数据库,相比其他的浏览器缓存LocalStorage 、cookie等相比,数据有以下特点
1.存储量大,理论上不封顶
2.同源策略是一样的
3.多数api采用的都是异步的方式,防止数据量大的时候阻塞其他的一些操作
4.通过对象仓库存储的方式
5.存储的类型比较丰富
6.能够为数据建立索引,提供查找性能
2.IndexedDB的特点
1.对象仓库,在indexedDB中是没有表的概念的,而是objectStore,一个数据库中可以包含多个objectStore,它是一个灵活的数据结构可以存放多种类型数据,里面储存的每条数据都和一个键相关联。键值可以指定也可以用数字递增也可以不指定但存储的类型会有差异。
2.事务性, 每次操作数据库都必须创建一个事务,2个参数(表名,是否可读写) db.transaction(storeName, ‘readwrite’)
3.基于请求,异步,indexedDB打开数据库,新建表等都是基于请求的,是一种异步的处理方式,必须在他回调函数中处理
创建
1.判断兼容性
var indexedDB =window.indexedDB ||window.webkitIndexedDB ||window.mozIndexedDB || window.msIndexedDB;
if (!indexedDB) {
console.log('你的浏览器不支持IndexedDB');
}
2.打开数据库
注:db 是全局变量,这边用的是vue 放在了data中
// 2\. 通过IDBFactory接口的open方法打开一个indexedDB的数据库实例
// 第一个参数: 数据库的名字,第二个参数:数据库的版本。返回值是一个:IDBRequest实例,此实例有onerror和onsuccess事件。
var IDBOpenDBRequest = indexedDB.open('yjDB', 1);
// 打开数据库成功后,自动调用onsuccess事件回调。
IDBOpenDBRequest.onsuccess = (e)=> {
this.db=e.target.result;
console.log('打开成功仓库yjDB',e.target.result);
};
// 打开数据库失败
IDBOpenDBRequest.onerror = function(e) {
console.log(e.currentTarget.error.message,"打开失败");
};
3.数据库初始化
注:数据初始化回调函数 早于 创建的成功回调
下方是创建了2个objectStroe 里面分别是3个索引,keyPath是关联你所需要存的数据
// 第一次打开成功后或者版本有变化自动执行以下事件:一般用于初始化数据库。
IDBOpenDBRequest.onupgradeneeded = (e)=> {
console.log("初始化或版本变动")
this.db = e.target.result; // 获取到 demoDB对应的 IDBDatabase实例,也就是我们的数据库。
// console.log('db');
if (!this.db.objectStoreNames.contains('yyyyy')) {
//如果表格不存在,创建一个新的表格(keyPath,主键 ; autoIncrement,是否自增),会返回一个对象(objectStore)
// objectStore就相当于数据库中的一张表。IDBObjectStore类型。
var objectStore = this.db.createObjectStore('yyyyy', {
keyPath: 'id',
// autoIncrement: true //自动生成主键
});
// //指定可以被索引的字段,unique字段是否唯一。类型: IDBIndex
objectStore.createIndex('name', 'name', {
unique: true //是否唯一, 意思是name 都是唯一的不能重复
});
objectStore.createIndex('age', 'age', {
unique: false
});
objectStore.createIndex('sex', 'sex', {
unique: false
});
console.log('数据库版本更改为: ' + e.version,'仓库1');
}
if (!this.db.objectStoreNames.contains('two')) {
//如果表格不存在,创建一个新的表格(keyPath,主键 ; autoIncrement,是否自增),会返回一个对象(objectStore)
// objectStore就相当于数据库中的一张表。IDBObjectStore类型。
var objectStore = this.db.createObjectStore('two', {
keyPath: 'id',
// autoIncrement: true //自动生成主键
});
// //指定可以被索引的字段,unique字段是否唯一。类型: IDBIndex
objectStore.createIndex('name', 'name', {
unique: true //是否唯一
});
objectStore.createIndex('height', 'height', {
unique: false
});
objectStore.createIndex('weight', 'weight', {
unique: false
});
console.log('数据库版本更改为: ' +e.version ,'仓库2');
}
};