joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

IndexDBWrapper 是一个简化 IndexedDB 操作的 JavaScript 库。以下是如何使用 IndexDBWrapper 库进行增删改查操作的示例。

首先,你需要引入 IndexDBWrapper 库。如果你使用的是 npm,可以通过以下命令安装:

npm install indexdb-wrapper

然后,你可以按照以下示例进行操作:

1. 初始化数据库

import IndexDBWrapper from 'indexdb-wrapper';

const db = new IndexDBWrapper('myDatabase', 1, [
  { name: 'myObjectStore', keyPath: 'id', indexes: [{ name: 'name', keyPath: 'name', unique: false }, { name: 'email', keyPath: 'email', unique: true }] }
]);

2. 添加数据(Create)

const newData = { id: 1, name: 'John Doe', email: 'john@example.com' };
db.add('myObjectStore', newData)
  .then(() => console.log('Data added successfully'))
  .catch(error => console.error('Unable to add data:', error));

3. 读取数据(Read)

db.get('myObjectStore', 1)
  .then(data => {
    if (data) {
      console.log('Data retrieved:', data);
    } else {
      console.log('No data found with ID:', 1);
    }
  })
  .catch(error => console.error('Unable to retrieve data:', error));

4. 更新数据(Update)

const updatedData = { id: 1, name: 'Jane Doe', email: 'jane@example.com' };
db.update('myObjectStore', updatedData)
  .then(() => console.log('Data updated successfully'))
  .catch(error => console.error('Unable to update data:', error));

5. 删除数据(Delete)

db.delete('myObjectStore', 1)
  .then(() => console.log('Data deleted successfully'))
  .catch(error => console.error('Unable to delete data:', error));

这些示例展示了如何使用 IndexDBWrapper 库进行基本的增删改查操作。请确保在实际应用中根据需要调整对象存储和索引的定义。

注意:IndexDBWrapper 库的具体 API 可能会随着版本更新而变化,建议查阅最新的官方文档以获取准确的信息。

posted on 2024-12-09 20:12  joken1310  阅读(85)  评论(0)    收藏  举报