Composables
useCraftQuery
Learn how to use the useCraftQuery composable.
This composable provides a simple way to fetch data from your Craft CMS Backend. It leverages js-craftcms-api to build query URLs and useAsyncData for fetching data asynchronously in an ssr friedndly way.
Element Types
<script setup lang="ts">
// query addresses
const { data, error } = await useCraftQuery('addresses').id(1).one()
// query assets
const { data, error } = await useCraftQuery('assets').id(1).one()
// query entry
const { data, error } = await useCraftQuery('entries').id(1).one()
// query users
const { data, error } = await useCraftQuery('users').id(1).one()
</script>
Note
data
and error
are Vue refs and they should be accessed with .value when used within the <script setup>
.
Execute Query
By using the one()
or the all()
methode the fetch gets executed. If you just building your query and are not executing it you need not to await it.
const query = useCraftQuery('entries').section('news')
// Fetch a single entry
const { data: singleEntry, error: singleError } = await query.one()
// Fetch all entries
const { data: allEntries, error: allError } = await query.all()
Available Methods
useCraftQuery
supports all methods from js-craftcms-api.
Note
For the full list of available methods, see the documentation here.
In addition, the following Nuxt-specific methods are available:
Method | Description | Type |
---|---|---|
one | Fetch one element | void |
all | Fetch all elements | void |
Example
const { data, error } = await useCraftQuery('entries')
.section('news')
.fields(['title'])
.limit(3)
.all()