1、main文件
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
import indexedDB from '@/utils/indexedDB.js';
import functionalModule from '@/utils/index.js';
Vue.prototype.$functionalModule = functionalModule;
Vue.prototype.$indexedDB = indexedDB;
indexedDB.openDB('myDB', 'mySurface', 1).then((res) => {
window.$db = res;
Vue.prototype.$db = res;
});
Vue.use(ElementUI);
Vue.config.productionTip = false;
setTimeout(() => {
new Vue({
render: h => h(App),
}).$mount('#app');
}, 0);
2、indexedDB文件
import { Message } from "element-ui";
function openDB(dbName, storeName, version = 1) {
return new Promise((resolve, reject) => {
let indexedDB =
window.indexedDB ||
window.mozIndexedDB ||
window.webkitIndexedDB ||
window.msIndexedDB,
db;
const request = indexedDB.open(dbName, version);
request.onsuccess = function (result) {
db = result.target.result;
resolve(db);
};
request.onerror = function (result) {
reject(result);
};
request.onupgradeneeded = function (result) {
db = result.target.result;
let objectStore = db.createObjectStore(storeName, {
keyPath: "id",
});
objectStore.createIndex("id", "id", { unique: false });
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("age", "age", { unique: false });
};
});
}
function addData(storeName, data) {
return new Promise((resolve, reject) => {
let request = window.$db
.transaction([storeName], "readwrite")
.objectStore(storeName)
.add(data);
request.onsuccess = function (result) {
Message({
message: '添加成功',
type: 'success'
});
resolve(result);
};
request.onerror = function (result) {
Message({
message: '添加失败',
type: 'error'
});
reject(result);
};
});
}
function getAll(storeName) {
return new Promise((resolve, reject) => {
let request = window.$db
.transaction(storeName, "readwrite")
.objectStore(storeName)
.getAll();
request.onsuccess = function (result) {
Message({
message: '获取成功',
type: 'success'
});
resolve(result);
};
request.onerror = function (result) {
Message({
message: '获取失败',
type: 'error'
});
reject(result);
};
});
}
function cursorGetData(storeName) {
return new Promise((resolve, reject) => {
let list = [],
request = window.$db
.transaction(storeName, "readwrite")
.objectStore(storeName)
.openCursor();
request.onsuccess = function (result) {
let cursor = result.target.result;
if (cursor) {
list.push(cursor.value);
cursor.continue();
} else {
Message({
message: '获取成功',
type: 'success'
});
resolve(list);
}
};
request.onerror = function (result) {
Message({
message: '获取失败',
type: 'error'
});
reject(result);
};
});
}
function fullValueSearch(storeName, indexName, indexValue) {
return new Promise((resolve, reject) => {
let list = [],
request = window.$db
.transaction(storeName, "readwrite")
.objectStore(storeName)
.index(indexName)
.openCursor(IDBKeyRange.only(indexValue));
request.onsuccess = function (result) {
let cursor = result.target.result;
if (cursor) {
list.push(cursor.value);
cursor.continue();
} else {
Message({
message: '搜索成功',
type: 'success'
});
resolve(list);
}
};
request.onerror = function (result) {
Message({
message: '搜索失败',
type: 'error'
});
reject(result);
};
});
}
function vagueLookup(storeName, searchName, searchValue, page, pageSize) {
return new Promise((resolve, reject) => {
let list = [],
total = 0,
len = 0,
request = window.$db
.transaction(storeName, "readwrite")
.objectStore(storeName)
.getAll();
request.onsuccess = function (result) {
let res = result.target.result;
Message({
message: '查询成功',
type: 'success'
});
res = res.sort((a, b) => new Date(b.updateDate) - new Date(a.updateDate));
total = res.length;
if (searchValue != '') {
res.forEach(item => { if (item[searchName].indexOf(searchValue) !== -1) list.push(item); });
} else {
list = res;
}
len = list.length > pageSize ? pageSize : list.length;
page = page == 1 ? 0 : (page - 1) * pageSize;
resolve({
total,
list: list.splice(page, len)
});
};
request.onerror = function (result) {
Message({
message: '查询失败',
type: 'error'
});
reject(result);
};
});
}
function updateDB(storeName, data) {
return new Promise((resolve, reject) => {
let request = window.$db
.transaction([storeName], "readwrite")
.objectStore(storeName)
.put(data);
request.onsuccess = function (result) {
Message({
message: '更新成功',
type: 'success'
});
resolve(result);
};
request.onerror = function (result) {
Message({
message: '更新失败',
type: 'error'
});
reject(result);
};
});
}
function deleteDB(storeName, id) {
return new Promise((resolve, reject) => {
let request = window.$db
.transaction([storeName], "readwrite")
.objectStore(storeName)
.delete(id);
request.onsuccess = function (result) {
Message({
message: '删除成功',
type: 'success'
});
resolve(result);
};
request.onerror = function (result) {
Message({
message: '删除失败',
type: 'error'
});
reject(result);
};
});
}
let indexedDB = {
deleteDB,
updateDB,
vagueLookup,
fullValueSearch,
cursorGetData,
getAll,
addData,
openDB,
};
export default indexedDB;
3、使用
3.1、查/删
methods: {
inputSearch(event) {
if (!event) this.getData();
},
async clickSearc() {
if (!this.searchName.replace(/\s*/g, "")) return this.$message.warning("请输入内容");
this.getData();
this.total = this.dataList.length;
},
clickDelete(row) {
this.$confirm("此操作将永久删除该数据, 是否继续?", "删除数据", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning",
})
.then(() => {
this.$indexedDB.deleteDB("mySurface", row.id);
this.getData();
})
.catch(() => {
this.$message({
type: "info",
message: "已取消删除",
});
});
},
async getData() {
let { total, list } = await this.$indexedDB.vagueLookup(
"mySurface",
"name",
this.searchName,
this.currentPage,
this.pageSize
);
this.dataList = list;
this.total = total;
},
},
3.2、增/改
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
let { id, name, age, politicalOutlook, createDate, updateDate } = this.ruleForm,
timeDateFormat = this.$functionalModule.timeDateFormat(),
obj = { id, name, age, politicalOutlook, createDate, updateDate, };
if (this.panelStatus == 0) {
obj.id = new Date().getTime();
obj.createDate = timeDateFormat;
obj.updateDate = timeDateFormat;
this.$indexedDB.addData("mySurface", obj);
} else {
obj.updateDate = timeDateFormat;
this.$indexedDB.updateDB("mySurface", obj);
}
this.$emit("closes");
this.ruleForm = {
name: null,
age: null,
politicalOutlook: 1,
};
this.$refs[formName].resetFields();
this.dialogFormVisible = false;
} else {
console.log("error submit!!");
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
},
}
4、完整代码
gitee(码云)develop分支 idexedDB文件夹
5、关于IndexedDB的详细介绍
1、CSDN-IndexedDB浏览器本地存储、缓存、数据库、介绍
|