Dexie有两种模式
-
静态的
-在大多数样品中使用最普遍的一种。
-
动态的
-代码中未指定架构。
静态模式
//
// Static Mode
//
const db = new Dexie('myDatabase');
db.version(1).stores({myTable1: '++'});
db.version(2).stores({myTable1: '++, foo'});
db.myTable1.add({foo: 'bar'}); // OK - dexie knows about myTable1!
动态模式
//
// Dynamic Mode
//
const db = new Dexie('myDatabase');
// FAIL: db.myTable1.add({foo: 'bar'}); // myTable1 is unknown to the API.
// Here, you must wait for db to open, and then access tables using db.table() method:
db.open().then(db => {
const myTable = db.table('myTable');
if (myTable) {
myTable.add({foo: 'bar'});
}
}).catch(error => {
console.error(error);
});
如果省略了任何版本()规范,DeXE将尝试用相同的名称打开任何现有的数据库,无论是版本还是模式。但它不会在db实例上创建隐式表属性。
当动态模式有用时
动态模式在构建应适应任何indexeddb数据库(如db explorer)的任意数据库实用程序时非常有用。当javascript代码在设计时不知道模式(期望查询哪些表和有哪些索引)时,动态模式也很有用。
静态模式的好处
-
无需等待db.open()完成。
-
需要时自动创建数据库。没有复杂的应用程序代码来处理数据库版本控制。
-
自动
DB population
需要的时候。
静态模式下的设计模式
数据库
import Dexie from 'dexie';
//
// Let this module do several things:
//
// * Create the singleton Dexie instance for your application.
// * Declare it's schema (and version history / migrations)
// * (Populate default data http://dexie.org/docs/Dexie/Dexie.on.populate)
//
export const db = new Dexie('myDatabase');
db.version(1).stores({
users: '++id,',
orgs: '++id,',
applications: '++id'
});
db.on('populate', () => {
return db.orgs.bulkAdd([
{'foo': 'bar'},
]);
});
应用程序js
import {db} from './db';
// Wherever you use the database, include your own db module
// instead of creating a new Dexie(). This way your code will
// always make sure to create or upgrade your database whichever
// of your modules that comes first in accessing the database.
//
// You will not have to take care of creation or upgrading scenarios.
//
// Let Dexie do that for you instead.
//
async function countOrgs() {
return await db.orgs.count();
}