Get started with Dexie in Vue
+
1. Create a Vue project
Here we refer to Vue's own Getting Started page.
2. Install dexie
3. Create a file db.js
(or db.ts
)
db.js
(or db.ts
)Applications typically have one single Dexie instance declared as its own module. This is where you declare which tables you need and how each table shall be indexed. A Dexie instance is a singleton throughout the application - you do not need to create it on demand. Export the resulting db
instance from your module so that components or other modules can use it to query or write to the database.
Using Typescript?
If you use Typescript, table properties (such as db.friends
) needs to be explicitly declared on a subclass of Dexie just to help out with the typings for your db instance, its tables and entity models.
4. Create a component that adds some data
Writing to the database can be done using Table.add(), Table.put(), Table.update() and Collection.modify() - see Dexie's quick reference for examples. Here we're gonna create a simple Vue component that allows the user to add friends into the database using Table.add().
5. Create a component that queries data
Write a simple component that just renders all friends in the database.
To be able to consume the observable returned from Dexie's liveQuery()
, we need to manage its subscription and unsubscription. For this sample, we use the hook useObservable() from @vueuse/rxjs.
Note that there are other ways to consume observables in vue - such as manually subscribe and unsubscribe in the lifecycle hooks if you prefer.
To make more detailed queries, refer to Dexie's quick reference for querying items.