vue中indexDb缓存使用

一、在main.js中引用indexDb

import Vue from 'vue'
import indexDb from './api/indexDb'

let storeName  = { index: ['tableView'], name: 'tableView', key: 'menuid' } //index:索引、name:表名、key:主键
indexDb.openDB('spreadTableView', 1, storeName, function(db){
  Vue.prototype.$tableDb = db //全局保存数据库
})

2、操作数据库方法

//举例,业务代码
...
<script>
import indexDb from './api/indexDb'
...
export default {
	...
	mounted(){
		let list = [{...}]
		let allDbData = indexDb.getAllData(this.$tableDb, 'tableView')
      	let flagIndex = indexDb.readAllData(this.$tableDb, list)
		if(flagIndex == -1){
        	indexDb.addData(this.$tableDb, 'tableView', list)
      	}else{
        	indexDb.updateData(this.$tableDb, 'tableView', list)
      	}
	}
	...
}
</script>

3、封装indexDb.js

export default {
    // indexedDB兼容
    indexedDB: window.indexedDB || window.webkitindexedDB || window.msIndexedDB || window.mozIndexedDB,
    /**
     * 打开数据库
     * 新对象储存空间newStore参数:newStore.name、newStore.key
     * 新增对象存储空间要更改数据库版本
     * @param {数据库名称} dbname 
     * @param {版本} version 
     * @param {数据库} db 
     * @param {配置} newStore 
     * @param {回调函数} callback 
     */
    openDB(dbname, version, newStore, callback) {
    	let db
        version = version || 1;
        const request = this.indexedDB.open(dbname, version);
        request.onerror = function () {
            console.log('IndexedDB数据库打开错误');
        };
        request.onsuccess = function (event) {
            db = event.target.result;
            if (callback && (typeof callback === 'function')) {
                callback(db);
            }
        };
        // onupgradeneeded,调用创建新的储存空间
        request.onupgradeneeded = function (event) {
            db = event.target.result;
            if (newStore) {
                if (!db.objectStoreNames.contains(newStore.name)) {
                    const objectStore = db.createObjectStore(newStore.name, {
                        keyPath: newStore.key,
                    });
                    newStore.index.forEach(item => {
                        objectStore.createIndex(item + '_index', item, {
                            unique: false
                        });
                    })
                }
            }
        };
    },
    /**
     * 删除数据库
     * @param {*} dbname 
     * @param {*} callback 
     */
    deleteDb(dbname, callback) {
        const deleteQuest = this.indexedDB.deleteDatabase(dbname);
        deleteQuest.onerror = function () {
            console.log('删除数据库出错');
        };
        deleteQuest.onsuccess = function () {
            if (callback && (typeof callback === 'function')) {
                callback();
            }
        }
    },
    /**
     * 关闭数据库
     * @param {*} dbname 
     */
    closeDB(dbname) {
        dbname.close();
        console.log('数据库已关闭');
    },
    /**
     * 删除数据
     * @param {*} db 
     * @param {*} storename 
     * @param {*} key 
     * @param {*} callback 
     */
    deleteData(db, storename, key, callback) {
        const store = db.transaction(storename, 'readwrite').objectStore(storename);
        const request = store.delete(key);
        request.onsuccess = function () {
            if (callback && (typeof callback === 'function')) {
                callback('删除成功');
            }
        }
        request.onerror = function () {
            if (callback && (typeof callback === 'function')) {
                callback('删除失败');
            }
        }

    },
    /**
     * 清空数据
     * @param {*} db 
     * @param {*} storename 
     * @param {*} callback 
     */
    clearData(db, storename, callback) {
        const store = db.transaction(storename, 'readwrite').objectStore(storename);
        const request = store.clear();
        request.onsuccess = function () {
            if (callback && (typeof callback === 'function')) {
                callback('清空数据成功');
            }
        }
        request.onerror = function () {
            if (callback && (typeof callback === 'function')) {
                callback('清空数据失败');
            }
        }
    },
    /**
     * 添加数据
     * @param {*} db 
     * @param {*} storename 
     * @param {*} obj 
     */
    addData(db, storename, list) {
        const store = db.transaction(storename, 'readwrite').objectStore(storename);
        list.forEach(ls => {
            const request = store.add(ls);
            request.onsuccess = function () {
                console.log('数据写入成功');
            };
            request.onerror = function () {
                console.log('数据写入失败');
            }
        })
    },
    /**
     * 更新数据
     * @param {*} db 
     * @param {*} storename 
     * @param {*} obj 
     */
    updateData(db, storename, list) {
        const store = db.transaction(storename, 'readwrite').objectStore(storename);
        list.forEach(ls => {
            const request = store.put(ls);
            request.onsuccess = function () {
                console.log('数据更新成功');
            };
            request.onerror = function () {
                console.log('数据更新失败');
            }
        })
    },
    /**
     * 根据主键获取数据
     * @param {*} db 
     * @param {*} storeName 
     * @param {*} key 
     * @returns 
     */
    getData(db, storeName, key){
        var objectStore = db.transaction(storeName).objectStore(storeName);
        var request = objectStore.get(key);
        request.onerror = function(event) {
            console.log('事务失败');
        };
        return new Promise((resolve, reject) => {
            request.onsuccess = function (e) {
                resolve(e.target.result)
            }
        })
    },
    /**
     * 根据索引获取数据
     * @param {*} db 
     * @param {*} storeName 
     * @param {*} field 
     * @param {*} val 
     */
    getDataByIndex(db, storeName, field, val) {
        const objectStore = db.transaction(storeName).objectStore(storeName);
        const index = objectStore.index(field + '_index');
        const request = index.get(val);
        return new Promise((resolve, reject) => {
            request.onsuccess = function (e) {
                resolve(e.target.result)
            }
        })
    },
    /**
     * 获取全部数据
     * @param {*} db 
     * @param {*} storeName 
     * @returns 
     */
    getAllData(db, storeName) {
        const objectStore = db.transaction(storeName).objectStore(storeName);
        const request = objectStore.openCursor();

        let data = [];
        return new Promise((resolve, reject) => {
            request.onsuccess = function (e) {
                var cursor = e.target.result;
                if (cursor) {
                    data.push(cursor.value);
                    cursor.continue();
                } else {
                    resolve(data)
                }
            }
        })
    },
    /**
     * 遍历全部数据,判断数据是否已存在于数据库
     * @param {*} allDbData
     * @param {*} list
     * @returns 
     */
     readAllData(allDbData, list){
        let flagIndex
        allDbData.then(res => { 
            flagIndex = res.findIndex(val=>{
                return (val.menuid == list[0].menuid)
            })
        })
        return flagIndex
     }
}
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值