Skip to content

Composition API

This library provides composable functions for seamless integration with the Vue Composition API. These are the primary entry points for interacting with your database and models in a type-safe, idiomatic way.

Provided Composables

onReActiveDatabaseReady

Registers a callback to be invoked after the Vue ReActiveRecord database is ready in the current Vue component lifecycle. This is the recommended way to run queries or mutations in components for SSR/hydration safety.

ts
import { ref } from 'vue'
import { useReActiveModel, onReActiveDatabaseReady } from '@nhtio/vue-re-active-record'

const Task = useReActiveModel('task')
const tasks = ref([])

onReActiveDatabaseReady(async () => {
  tasks.value = await Task.all()
})
  • The callback is awaited if it returns a Promise.
  • In SSR, the callback runs immediately after mount (with stub data).
  • In the browser, it waits for the real database to be ready before running.
  • This prevents hydration mismatches and is the safest way to load data in components.

See the API documentation for onReActiveDatabaseReady for details.

useReActiveDatabase

Injects and returns the Vue ReActiveRecord database instance from the current Vue application context. Useful for accessing global database methods or metadata.

ts
import { useReActiveDatabase } from '@nhtio/vue-re-active-record'

const db = useReActiveDatabase()

See the API documentation for useReActiveDatabase for details.

useReActiveModel

Retrieves a model constructor for a specific model defined in your configuration. This composable is the primary way to query, create, update, and delete records for a given model.

TypeScript users will get full type inference for their models if they augment the types as shown above.

Example (based on the Example Implementation):

ts
import { ref, onMounted } from 'vue'
import { useReActiveModel } from '@nhtio/vue-re-active-record'

const Task = useReActiveModel('task')
const tasks = ref([])

onMounted(async () => {
  // Query all tasks, ordered by completion and priority
  const collection = await Task.query()
    .orderBy('completed', 'asc')
    .orderBy('priority', 'desc')
    .orderBy('id', 'asc')
    .fetch()
  tasks.value = collection.$value
})

// To create a new task:
await Task.create({ title: 'New Task', completed: false, priority: 3 })

See the API documentation for useReActiveModel for details on usage and type inference.