标题:
客户端(浏览器端)数据存储技术概览(2)
[打印本页]
作者:
yuyang911220
时间:
2017-4-23 20:05
标题:
客户端(浏览器端)数据存储技术概览(2)
优点,缺点和浏览器支持
和 Local Storage 一样
IndexedDB
IndexedDB 是一种更复杂和全面地客户端数据存储方案,它是基于 JavaScript、面向对象的和数据库的,能非常容易地存储数据和检索已经建立关键字索引的数据。
在构建渐进式Web应用一文中,我已经介绍了怎么使用 IndexedDB 来创建一个离线优先的应用。
IndexedDB 的基本 CRUD 操作
注:在示例中,我使用了 Jake’s Archibald 的 IndexedDB Promised library, 它提供了 Promise 风格的IndexedDB方法
使用 IndexedDB 在浏览器端存储数据比上述其它方法更复杂。在我们能创建/读取/更新/删除任何数据之前,首先需要先打开数据库,创建我们需要的stores(类似于在数据库中创建一个表)。
function OpenIDB() {
return idb.open('SampleDB', 1, function(upgradeDb) {
const users = upgradeDb.createObjectStore('users', {
keyPath: 'name'
});
});
}
创建或者更新store中的数据:
// 1. Open up the database
OpenIDB().then((db) => {
const dbStore = 'users';
// 2. Open a new read/write transaction
with the store within the database
const transaction = db.transaction(dbStore, 'readwrite');
const store = transaction.objectStore(dbStore);
// 3. Add the data to the store
store.put({
name: 'Ire Aderinokun',
age: 25
});
// 4. Complete the transaction
return
transaction.complete;
});
检索数据:
// 1. Open up the database
OpenIDB().then((db) => {
const dbStore = 'users';
// 2. Open a new read-only
transaction
with the store within the database
const transaction = db.transaction(dbStore);
const store = transaction.objectStore(dbStore);
// 3. Return the data
return store.get('Ire Aderinokun');
}).then((item) => {
console.log(item);
})
删除数据:
// 1. Open up the database
OpenIDB().then((db) => {
const dbStore = 'users';
// 2. Open a new read/write transaction
with the store within the database
const transaction = db.transaction(dbStore, 'readwrite');
const store = transaction.objectStore(dbStore);
// 3. Delete the data corresponding to the passed key
store.delete('Ire Aderinokun');
// 4. Complete the transaction
return
transaction.complete;
})
如果你有兴趣了解更多关于IndexedDB的使用,可以阅读我的这篇关于怎么在渐进式Web应用(PWA)使用IndexedD。
IndexedDB 的优点
能够处理更复杂和结构化的数据
每个’database’中可以有多个’databases’和’tables’
更大的存储空间
对其有更多的交互控制
IndexedDB 的缺点
比 Web Storage API 更难于应用
浏览器支持
IE10+/Edge12+/Firefox 4+/Chrome 11+/Safari 7.1+/Opera 15+(caniuse)
对比
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0