目前在寻找前端存储数据的方法,在网上看见了IndexedDB,感觉很符合要求。
通过学习,写了一个完整的增删改查的实例。
IndexedDB 就是浏览器提供的本地数据库,它可以被网页脚本创建和操作。IndexedDB 允许储存大量数据,提供查找接口,还能建立索引。这些都是 LocalStorage 所不具备的。就数据库类型而言,IndexedDB 不属于关系型数据库(不支持 SQL 查询语句),更接近 NoSQL 数据库
IndexedDB中的基本对象
- IDBDatabase 数据库对象
- IDBObjectStore 对象(表)
- IDBIndex 索引
- IDBTransaction 事务
- IDRequest 请求
- IDBKeyRange 主键集合
主要操作
- 打开数据库
IndexedDB
var request = window.indexedDB.open(db, version);
db
(数据库) version
(版本号)
open
方法回返回IDRequest对象。对象中有事件error
、success
、upgradeneeded
,新建数据库与打开数据库是同一个操作。如果指定的数据库不存在,就会新建。
- error 事件
- success事件
- upgradeneeded事件
//新建数据库以后,第一件事是新建对象仓库(即新建表)
request.onupgradeneeded = function(event){
db = event.target.result;
var objectStore;
if(!db.objectStoreNames.contains('person')){
objectStore = db.createObjectStore('person',{ keyPath:'id'});
}
}
- 新增数据
var transaction = db.transaction(['person'],'readwrite').
var objectStore = transaction.objectStore('person');
var request = objectStore.add({ id:1, name:'张三', age:24, email:'zhangsan@example.com'});
request.onsuccess = function(event){
console.log('数据写入成功');
};
request.onerror =function(event){
console.log('数据写入失败');
}
- 读取数据
var transaction = db.transaction(['person']);
var objectStore = transaction.objectStore('person');
var request = objectStore.get(1);
request.onerror = function(event){
console.log('事务失败');
};
request.onsuccess =function( event){
if(request.result){
console.log('Name: '+ request.result.name);
console.log('Age: '+ request.result.age);
console.log('Email: '+ request.result.email);
}else{
console.log('未获得数据记录');
}
}
- 更新数据
var transaction = db.transaction(['person'],'readwrite')
var objectStore = transaction.objectStore('person')
var request = objectStore.put({ id:1, name:'李四', age:35, email:'lisi@example.com'});
request.onsuccess = function(event){
console.log('数据更新成功');
};
request.onerror = function(event){
console.log('数据更新失败');
}
- 删除数据
var transaction = db.transaction(['person'],'readwrite')
var objectStore = transaction.objectStore('person')
var request = objectStore.delete(1);
request.onsuccess =function(event){
console.log('数据删除成功');
}
- 使用索引, 主要用户查询
objectStore.createIndex('name','name',{ unique:false});
var transaction = db.transaction(['person'],'readonly');
var store = transaction.objectStore('person');
var index = store.index('name');
var request = index.get('李四');
request.onsuccess = function(e){
}
示例图
实例需要用
- Vue
页面布局
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IndexedDB 实例 (增删改查)</title>
<link rel="stylesheet" href="../../css/mui.css" />
<script type="text/javascript" src="../../js/mui.js" ></script>
<script src="../../js/vue.min.js"></script>
<script type="text/javascript" src="db.js" ></script>
</head>
<body>
<div id="app">
<div class="mui-content-padded">
<button @tap="delteItem" class="mui-btn mui-btn-blue">删除</button>
<button @tap="saveItem" class="mui-btn mui-btn-green">保存</button>
<button @tap="addItem" class="mui-btn mui-btn-blue">新增</button>
<div v-for="item in items" @tap="tapItem(item)">
<input type="checkbox" :checked="item.check" v-model="item.check"/>
<label style="width: 100px;display: inline-block;">{{item.id}}</label>
<input style="width: 100px;" v-model="item.name" />
</div>
</div>
</div>
</body>
</html>
js部分
// db.open('test',1);
var appVue = new Vue({
el: "#app",
data: {
selectItem: null,
items: []
},
methods: {
saveItem: function(){
if(!appVue.selectItem){
mui.toast("请选择一条数据!");
return;
}
var item = appVue.selectItem;
db.save('user', item, function(event){
if(event.type == "error") {
console.log(event.target.error.message);
}
db.query('user', {}, function(result){
console.log("查询结果" + JSON.stringify(result));
for(var i = 0; i < result.length; i++){
var _row = result[i];
_row["check"] = false;
}
appVue.items = result;
});
});
},
delteItem: function(){
if(!appVue.selectItem){
mui.toast("请选择一条数据!");
return;
}
var id = appVue.selectItem.id;
db.delete('user', id, function(event){
db.query('user', {}, function(result){
console.log("查询结果" + JSON.stringify(result));
for(var i = 0; i < result.length; i++){
var _row = result[i];
_row["check"] = false;
}
appVue.items = result;
});
});
},
tapItem: function(item){
if(item.check) {
item.check = false;
appVue.selectItem = null;
} else {
item.check = true;
appVue.selectItem = item;
}
},
addItem: function(){
db.add('user', {id: Math.random(), name: "yinc"}, function(event){
db.query('user', {}, function(result){
console.log("查询结果" + JSON.stringify(result));
for(var i = 0; i < result.length; i++){
var _row = result[i];
_row["check"] = false;
}
appVue.items = result;
});
});
}
}
});
/**
* 打开数据库
*/
db.open('dbuser', 1, function(){
console.log("db打开成功");
db.query('user', {}, function(result){
console.log("查询结果" + JSON.stringify(result));
for(var i = 0; i < result.length; i++){
var _row = result[i];
_row["check"] = false;
}
appVue.items = result;
});
},function(){
console.log("db打开失败");
});
IndexedDB 封装部分
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction || {READ_WRITE: "readwrite"};
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
if (!window.indexedDB) {
console.log("浏览器不支持indexedDB");
} else {
console.log("可以使用indexedDB");
}
function DB(){
var me = this;
var _db = null;
me.isOpened = false;
// IDBOpenDBRequest
/**
* 打开一个数据库
* @param {Object} database
* @param {Object} version
* @param {Object} success
* @param {Object} error
* @param {Object} update
*/
me.open = function(database, version, success, error, update){
var request = window.indexedDB.open(database, version);
request.onsuccess = function(event){
_db = request.result;
me.isOpened = true;
success(event);
};
request.onerror = error;
request.onupgradeneeded = function(event){
var version = event.newVersion;
var oldVersion = event.oldVersion;
var db = event.target.result;
//新建表
if(version < 2) {
var objectStore = db.createObjectStore("user", { keyPath: "id" });
objectStore.createIndex("name", "name", {unique: false});
}
_db = db;
}
}
/**
* 新增数据
*/
me.add = function(table, item, fsuccess){
if(!_isAllow()) return;
var transaction = _db.transaction([table], "readwrite");
var objectStore = transaction.objectStore(table);
var request = objectStore.add(item);
request.onsuccess = fsuccess;
request.onerror = fsuccess;
}
me.save = function(table, item, fsuccess){
if(!_isAllow()) return;
var transaction = _db.transaction([table], "readwrite");
var objectStore = transaction.objectStore(table);
var request = objectStore.put(item);
request.onsuccess = fsuccess;
request.onerror = fsuccess;
}
/**
* 删除数据
*/
me.delete = function(table, key, fsuccess){
if(!_isAllow()) return;
var transaction = _db.transaction([table], "readwrite");
var objectStore = transaction.objectStore(table);
var request = objectStore.delete(key);
request.onsuccess = fsuccess;
request.onerror = fsuccess;
}
function _isAllow(){
if(!me.isOpened){
mui.toast("数据库未开启!")
return false;
}
return true;
}
/**
* 修改数据
*/
me.update = function(){
if(!_isAllow()) return;
}
me.query = function(table,filter,fsuccess){
if(!_isAllow()) return;
var transaction = _db.transaction([table], "readwrite");
var objectStore = transaction.objectStore(table);
var cursor = objectStore.openCursor();
var result = [];
cursor.onsuccess = function(event){
var _cursor = event.target.result;
if (_cursor) {
console.log("Name for SSN " + _cursor.key + " is " + _cursor.value.name);
_cursor.continue();
result.push(_cursor.value);
} else {
fsuccess(result);
}
}
cursor.onerror = function(){
}
}
}
var db = new DB();
网友评论