封装如下:

indexDBOperate.js
export class IndexDBOperate {

    db = null // 数据库实例

    databaseName = null // 数据库名称

    version = null // 数据库版本

    objStoName = null // 表或对象仓库名称

    constructor(databaseName, version, objStoName, indexObj, successFunc) {

        this.databaseName = databaseName
this.version = version
this.objStoName = objStoName // 若无此数据库则会创建
const request = window.indexedDB.open(databaseName, version)
request.onerror = e => {
console.log('数据库打开报错')
} request.onsuccess = e => {
this.db = request.result
const db = request.result console.log('数据库打开成功')
// 建表或对象仓库,id作为主键 successFunc(db)
} // 如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件
// 第一次打开数据库时,会先触发upgradeneeded事件,然后触发success事件
request.onupgradeneeded = e => {
// console.log('数据库打开/创建报错')
// this.db = e.target.result
const db = e.target.result if (!db.objectStoreNames.contains(objStoName)) {
// 建表
const objectStore = db.createObjectStore(objStoName, { keyPath: 'id' }); // 新建索引(索引名称、索引所在的属性、配置对象(说明该属性是否包含重复的值))
objectStore.createIndex(indexObj.indexName, indexObj.IndexAattrOf, indexObj.config)
} } request.blocked = e => {
// console.log('上一次的数据库连接还未关闭')
}
} // 创建
createData = data => {
const request = this.db.transaction([`${this.objStoName}`], 'readwrite')
.objectStore(`${this.objStoName}`)
.add(data) request.onsuccess = e => {
console.log('数据写入成功')
} request.onerror = e => {
console.log('数据写入失败', e.target.error)
}
} // 更新
updateData = data => {
const request = this.db.transaction([`${this.objStoName}`], 'readwrite').objectStore(`${this.objStoName}`)
.put(data) request.onsuccess = e => {
// console.log('数据更新成功')
}; request.onerror = e => {
// console.log('数据更新失败')
}
} // 读
retrieveData = (id, successFunc) => {
const transaction = this.db.transaction([`${this.objStoName}`])
const objectStore = transaction.objectStore(`${this.objStoName}`)
const request = objectStore.get(id) request.onerror = e => {
// console.log('事务失败')
}; request.onsuccess = e => {
if (request.result) {
successFunc(request.result)
// console.log('Name: ' + request.result.name)
// console.log('Age: ' + request.result.age)
// console.log('Email: ' + request.result.email)
} else {
// console.log('未获得数据记录')
}
};
} // 遍历
readAllData = successFunc => {
const objectStore = this.db.transaction([`${this.objStoName}`], 'readwrite')
.objectStore(`${this.objStoName}`) objectStore.openCursor().onsuccess = e => {
const cursor = e.target.result if (cursor) {
successFunc(cursor)
cursor.continue()
// console.log('Id: ' + cursor.key)
// console.log('Name: ' + cursor.value.name)
// console.log('Age: ' + cursor.value.age)
// console.log('Email: ' + cursor.value.email)
} else {
// console.log('没有更多数据了!')
}
};
} // 遍历(加入模糊搜索)
fuzzySearchData = (field, keyWord, successFunc) => {
const objectStore = this.db.transaction([`${this.objStoName}`], 'readwrite')
.objectStore(`${this.objStoName}`)
const data = [] objectStore.openCursor().onsuccess = e => {
const cursor = e.target.result if (cursor) {
if (cursor.value[`${field}`].indexOf(keyWord) >= 0) {
data.push(cursor.value)
}
cursor.continue() // console.log('Id: ' + cursor.key)
// console.log('Name: ' + cursor.value.name)
// console.log('Age: ' + cursor.value.age)
// console.log('Email: ' + cursor.value.email)
} else {
// console.log('没有更多数据了!')
successFunc(data)
}
};
} deleteData = id => {
const request = this.db.transaction([`${this.objStoName}`], 'readwrite')
.objectStore(`${this.objStoName}`)
.delete(id) request.onsuccess = e => {
// console.log('数据删除成功')
};
} // 通过索引获取数据
retrieveByIndex = (indexName, searchTerm, successFunc) => {
const transaction = this.db.transaction([`${this.objStoName}`], 'readonly')
const store = transaction.objectStore(`${this.objStoName}`)
const index = store.index(`${indexName}`)
const request = index.get(`${searchTerm}`) request.onsuccess = e => {
const { result } = e.target
console.log(e.target)
if (result) {
// ...
successFunc(result)
} else {
// ...
}
}
}
}// 封装by 有蚊子 @2019.11.20

使用示例:

  // indexDB调用示例
handleDB = () => {
const indexDB = new IndexDBOperate('chat_help_db', 1, 'chat_help', {
indexName: 'name',
IndexAattrOf: 'name',
config: {
unique: false,
},
}, db => { indexDB.fuzzySearchData('name', 'a', result => {
console.log(result)
})
indexDB.createData({ id: 7, name: 'aaa' })
indexDB.updateData({ id: 3, name: 'a2' })
indexDB.retrieveByIndex('name', 'a', result => {
console.log(result)
})
indexDB.deleteData(7)
indexDB.retrieveData(1, result => {
console.log(result)
})
indexDB.readAllData(result => {
console.log(result)
})
})
}

参考资料:

1. http://www.ruanyifeng.com/blog/2018/07/indexeddb.html 阮一峰indexdb使用

2.https://wangdoc.com/javascript/bom/indexeddb.html#idbindex-%E5%AF%B9%E8%B1%A1 indexdb api文档

使用ES6 Class封装的IndexDB 操作类,并实现模糊搜索的更多相关文章

  1. 封装一个redis操作类来操作hash格式

    最近项目要用redis,依然是基于tp3.2. 发现thinkphp3.2自带的缓存类并不好使用,就自己封装了一个 目前只支持hash格式,其他数据类型的操作后面用到的时候再补充 <?php / ...

  2. php 封装mysql 数据库操作类

    <?phpheader('content-type:text/html;charset=utf-8');//封装mysql   连接数据库php_mysql//封装mysql   连接数据库ph ...

  3. php 封装Mysql数据库操作类

    花了点时间写了个基于php5.3的Mysql类 $mysql = new Mysql('host','user','pass','db') bool Mysql::insert("表&quo ...

  4. php封装的sqlite操作类

    sqlite在php中是默认安装的本地小型化数据库,类似于xml的小型数据库,但sqlite功能更强. sqlite.class.php文件: <?php class sqliteDB{ pri ...

  5. 我的DbHelper数据操作类

    其实,微软的企业库中有一个非常不错的数据操作类了.但是,不少公司(起码我遇到的几个...),对一些"封装"了些什么的东西不太敢用,虽然我推荐过微软的企业库框架了...但是还是要&q ...

  6. DbHelper数据操作类

    摘要:本文介绍一下DbHelper数据操作类 微软的企业库中有一个非常不错的数据操作类.但是,不少公司(起码我遇到的几个...),对一些"封装"了些什么的东西不太敢用,虽然我推荐过 ...

  7. 我的DbHelper数据操作类(转)

    其实,微软的企业库中有一个非常不错的数据操作类了.但是,不少公司(起码我遇到的几个...),对一些"封装"了些什么的东西不太敢用,虽然我推荐过微软的企业库框架了...但是还是要&q ...

  8. 自己封装的poi操作Excel工具类

    自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...

  9. Redis操作Hash工具类封装,Redis工具类封装

    Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...

随机推荐

  1. Luogu P5416 [CTSC2016]时空旅行

    第一次写线段树分治的题目,没想到是道这么毒的题233 首先发现题目里的\((x,y,z,c)\)就是在放屁,只有\((x,c)\)是有用的 因此我们可以把题意转化为,在某一个时间节点上,求出所有元素的 ...

  2. [LOJ 2083][UOJ 219][BZOJ 4650][NOI 2016]优秀的拆分

    [LOJ 2083][UOJ 219][BZOJ 4650][NOI 2016]优秀的拆分 题意 给定一个字符串 \(S\), 求有多少种将 \(S\) 的子串拆分为形如 AABB 的拆分方案 \(| ...

  3. vue_day05

    目录 vue前后端交互: vue 分离前后端交互: vue前端发送请求: vue请求插件--axios: main.js配置: 前端朝后端请求传参方式: django后端返回数据样式: vue配置El ...

  4. Note | Ubuntu

    目录 0. 教程 1. 安装 2. 系统 0. 教程 <Linux就该这么学>:https://www.cnblogs.com/RyanXing/p/9462850.html 1. 安装 ...

  5. Git修改和配置用户名和邮箱

    git在push/push to时需要使用到user.name和user.email,切记一定要现配置好查看user.name/user.email git config user.name git ...

  6. python批量裁剪图片

    """用Pythonp批量裁剪图片""" from PIL import Imageimport matplotlib.pyplot as ...

  7. 转:对softmax讲解比较清楚的博客

    https://blog.csdn.net/wgj99991111/article/details/83586508

  8. Window权限维持(二):计划任务

    Windows操作系统提供了一个实用程序(schtasks.exe),使系统管理员能够在特定的日期和时间执行程序或脚本.这种行为可作为一种持久性机制被red team利用.通过计划任务执行持久性不需要 ...

  9. 简单ALV得演示(用到了ALV可编辑及保存后修改数据库)

    *&---------------------------------------------------------------------* *& Report YPMRP010_ ...

  10. Swagger实例分享(VS+WebApi+Swashbuckle)

    Swagger实例分享(VS+WebApi+Swashbuckle) Swagger可以很方便的为发布的WebApi自动生成优雅的文档,不需额外自己编写,只需为项目配置好,是一个很好用的工具,做一个简 ...