Query with the $prismic Object

The $prismic object is injected globally into all projects with the prismic-nuxt module, and all projects with SliceMachine installed. Read more about it here.

To retrieve the content of your document's Slice Zone, you can use the slice-zone component. For all other content, like content outside of the document body, you can use the following methods.

Query helpers and options

The $prismic object includes a collection of helper functions for querying the API, on $prismic.api. These include:

$prismic.api.getByUID: get a single document by specifying the type and UID

$prismic.api.getSingle: get a singleton by specifying the type

$prismic.api.query: query content by predicates

All of the query helpers can also accept an options object, to specify language, orderings, pagination, and more. Read more about how to use query helpers and query options.

Use cases

1. Querying from a page

On a page, you can query the API inside Nuxt's asyncData() method. Here's what a query inside pages/_uid.vue could look like:

export default {
  async asyncData({ $prismic, params, error }) {
    const document = await $prismic.api.getByUID('page', params.uid)

    if (document) {
      return { document }
    } else {
      error({ statusCode: 404, message: 'Page not found' })
    }
  }
}

2. Querying from a component or layout

In components and layouts, you can query data inside Nuxt's fetch() method. Unlike asyncData(), fetch() does not return data but can instead update data that is already defined.

export default {
  data() {
    return {
      headerData: {}
    }
  },
  async fetch() {
    this.headerData = await this.$prismic.api.getSingle('header')
  }
}

3. Querying from the Vuex Store

To make data available across your app, you can query Prismic from the Vuex Store.

export const state = () => ({
  settings: {}
})

export const mutations = {
  setSettings(state, settings) {
    state.settings = settings
  }
}

export const actions = {
  async loadSettings({ commit }) {
    const settings = await this.$prismic.api.getSingle('site_settings')
    commit('setSettings', settings)
  }
}
9 Rue de la Pierre Levée, 75011 Paris