@prismicio/vue - v4
@prismicio/vue
is the official Prismic package for creating web apps with Prismic and Vue.js.
Package version
Are you on version 3 of @prismicio/vue
? Follow our instructions to upgrade to version 4.
Version 3 and above of this package target Vue 3. To integrate Vue 2 with Prismic use version 2 of this package, @prismicio/vue@^2
.
@prismicio/vue
provides three main functionalities:
- Plugin: It provides an instance of the client and helper functions from
@prismicio/client
, preconfigures and exposes helpers from the same package, and registers components globally. - Components: It provides a collection of components to render content from Prismic documents.
- Client composables: It provides Vue composables to use with the Composition API to query content from a Prismic repository.
This package can only be used in a Vue project. It provides @prismicio/client
and so you don't need to install it explicitly. However, if you need to import things directly from it for any reason, you can still install the client alongside @prismicio/vue
.
Since this is a general-purpose Vue.js library, it can be used in simple setups like Vue CLI and Vite or in more advanced frameworks that use Vue, like Nuxt, although we also offer a specific integration for the latter: @nuxtjs/prismic
.
- npm
- Yarn
npm install @prismicio/vue
yarn add @prismicio/vue
The plugin allows settings for @prismicio/vue
's Vue components, composables, client and helpers to be configured in one central location. This is done using Vue plugin system.
Here's an example of setting up the plugin in a prismic.js
file.
import { createPrismic } from "@prismicio/vue";
const prismic = createPrismic({ endpoint: "your-endpoint" });
export default prismic;
Additional options for createPrismic()
are described below.
Once created, you can add the plugin to your Vue application.
import { createApp } from "vue";
import App from "./App.vue";
import prismic from "./prismic";
createApp(App).use(prismic).mount("#app");
createPrismic(options)
A factory function used to create a configured plugin instance to be used by the Vue application.
import { createApp } from "vue";
import { createPrismic } from "@prismicio/vue";
import App from "./App.vue";
const prismic = createPrismic({
endpoint: "your-repo-name",
});
createApp(App).use(prismic).mount("#app");
createPrismic()
object accepts the following properties. Only endpoint
or client
are mandatory (at least one of the two):
endpoint
A Prismic repository endpoint to init the plugin's @prismicio/client instance used to fetch content from a Prismic repository with. Can be either just the repository ID (your-repo-name) or the full API endpoint (https://your-repo-name.cdn.prismic.io/api/v2).
clientConfig
An optional object used to configure the created @prismicio/client instance further. See the @prismicio/client documentation for configuration options.
client
A @prismicio/client instance used to fetch content from a Prismic repository to configure the plugin with. This option is to be used instead of the two previous ones (endpoint & clientConfig).
linkResolver
An optional link resolver function used to resolve links to Prismic documents when not using the route resolver parameter with @prismicio/client. See the link resolver documentation.
richTextSerializer
An optional rich text serializer to customize the way rich text fields are rendered.
injectComponents
Whether or not to inject components globally. Defaults to true.
components
An optional options object used to configure injected components default behavior, see details below.
components.linkBlankTargetRelAttribute
Value of the rel attribute to use on links rendered with target="_blank". Defaults to "noopener noreferrer".
components.linkInternalComponent
An HTML tag name, a component, or a functional component used to render internal links. Defaults to Vue Router <RouterLink>
component if available.
components.linkExternalComponent
An HTML tag name, a component, or a functional component used to render external links. Defaults to "a".
components.imageComponent
An HTML tag name, a component, or a functional component used to render images. Defaults to "img".
components.imageWidthSrcSetDefaults
Default widths to use when rendering an image with widths="defaults". Defaults to @prismicio/client defaults.
components.imagePixelDensitySrcSetDefaults
Default pixel densities to use when rendering an image with pixel-densities="defaults". Defaults to @prismicio/client defaults.
components.sliceZoneDefaultComponent
A component or a functional component rendered if a component mapping from the components prop cannot be found. Defaults to null when process.env.NODE_ENV === "production". When not, it defaults to a TODO slice component.
usePrismic()
this.$prismic
By default, the plugin configures and injects in Vue context:
- An
@prismicio/client
instance atclient
, as well aspredicate
andcookie
asText
,asHTML
,asLink
,asLinkAttrs
,asDate
,asImageSrc
,asImageWidthSrcSet
,asImagePixelDensitySrcSet
helpers from@prismicio/client
All those properties and methods can be accessed using the usePrismic()
composable when using the Composition API.
import { usePrismic } from "@prismicio/vue";
const { client, asDate } = usePrismic();
// ...
When using the Options API they can be accessed through the Vue instance.
export default {
mounted() {
this.$prismic.client(/* ... */);
this.$prismic.asDate(/* ... */);
// ...
}
};
All components described below will also be injected globally by the plugin when leaving the injectComponents
option to true
. No imports are required.
<template>
<PrismicRichText :field="document.data.myRichTextField" />
</template>
@prismicio/vue
provides a collection of components to render content from Prismic documents. These components are injected globally when the plugin is configured.
// Not necessary when using the plugin
import { PrismicRichText } from "@prismicio/vue";
A Vue component that renders content from a Prismic rich text or title field.
By default, HTML elements are rendered for each piece of content. For example, a heading1
block will render an <h1>
HTML element. Internal links will use Vue Router, if available, for routing.
<PrismicRichText :field="document.data.myRichTextField" />
This component wraps its output in a <div>
tag, if you need another wrapper tag, or component, to be used, use the wrapper
prop.
<PrismicRichText :field="document.data.myRichTextField" wrapper="article" />
A fallback
prop can be provided to define an HTML string to render when the rich text or title field is empty. If a fallback
prop is not provided, ""
(nothing) is rendered by default for an empty field.
<PrismicRichText :field="document.data.myRichTextField" fallback="<p>No content</p>" />
By default, if you're using the plugin, the component will use the link resolver, and a custom rich text serializer is provided through its linkResolver
and serializer
options. In any case, you can still provide those explicitly to the component using the linkResolver
and serializer
props:
<PrismicRichText
:field="document.data.myRichTextField"
:link-resolver="linkResolver"
:serializer="serializer"
/>
For lower-level use cases, a composable is also available to replicate this component behavior. It uses the same props as options, except the wrapper
prop, which is omitted.
import { usePrismicRichText } from "@prismicio/vue";
const { html } = usePrismicRichText({ field: document.data.myRichTextField });
// Not necessary when using the plugin
import { PrismicText } from "@prismicio/vue";
Vue component that renders content from a Prismic rich text or title field as plain text.
<PrismicText :field="document.data.myTitleField" />
This component wraps its output in a <div>
tag. To use a different wrapper tag or wrapper component, use the wrapper
prop.
<PrismicText :field="document.data.myTitleField" wrapper="h1" />
A fallback
prop can be provided to define a string to render when the rich text or title field is empty. If a fallback
prop is not provided, ""
(nothing) is rendered by default for an empty field.
<PrismicText :field="document.data.myTitleField" fallback="No content" />
For lower-level use cases, a composable is also available to replicate this component behavior. It uses the same props as options, except the wrapper
prop, which is omitted.
import { usePrismicText } from "@prismicio/vue";
const { text } = usePrismicText({ field: document.data.myTitleField });
// Not necessary when using the plugin
import { PrismicLink } from "@prismicio/vue";
Vue component that renders a link from a Prismic link field or a Prismic document.
This component automatically resolves a field's link to a URL. It also applies the correct target
and rel
props if Open in new tab is enabled for the field.
<PrismicLink :field="document.data.myLinkField">
Click me
</PrismicLink>
You can also create a link from a document the very same way.
<PrismicLink :field="document">
Click me
</PrismicLink>
By default, the <RouterLink>
component from Vue Router is used to render internal links, and an <a>
HTML element is used for external ones.
These defaults can be overridden globally using the plugin components.linkInternalComponent
and components.linkExternalComponent
options or locally by using the internalComponent
and externalComponent
props.
<PrismicLink
:field="document.data.myLinkField"
:internalComponent="MyInternalLink"
:externalComponent="MyExternalLink"
>
Click me
</PrismicLink>
If your app uses route resolvers when querying for documents, providing a link resolver is optional.
If your app does not use the route resolver, or requires an override for specific URLs, the component will use the link resolver provided to the plugin through its linkResolver
option if you're using it or through the component's linkResolver
prop. The linkResolver
component prop will take precedence over the linkResolver
plugin option.
<PrismicLink
:field="document.data.myLinkField"
:linkResolver="linkResolver"
>
Click me
</PrismicLink>
By default, if "Open in new tab" is enabled for the field, the component will render the rel
attribute with a value of "noopener noreferrer"
.
This default can be overridden globally using the plugin components.linkBlankTargetRelAttribute
option or locally by using the blankTargetRelAttribute
prop.
<PrismicLink
:field="document.data.myLinkField"
blank-target-rel-attribute="noopener"
>
Click me
</PrismicLink>
The target
and rel
props allows your to set explicit value for those attributes.
<PrismicLink
:field="document.data.myLinkField"
target="_top"
rel="noopener"
>
Click me
</PrismicLink>
For lower-level use cases, a composable is also available to replicate this component behavior. It uses the same props as options.
import { usePrismicLink } from "@prismicio/vue";
const {
type, // suggested, unresolved, component to render
href,
target,
rel
} = usePrismicLink({ field: document.data.myLinkField });
// Not necessary when using the plugin
import { PrismicImage } from "@prismicio/vue";
<PrismicImage :field="document.data.myImageField" />
By default, an <img />
HTML element is used to render images.
This default can be overridden globally using the plugin components.imageComponent
option or locally by using the imageComponent
prop.
<PrismicImage
:field="document.data.myImageField"
:image-component="MyImageComponent"
/>
When using a custom image component, it receives src
, srcset
, alt
, and copyright
values as additional props.
Imgix parameters can be applied to the rendered image using the imgix-params
prop.
<PrismicImage
:field="document.data.myImageField"
:imgix-params="{ sat: 100 }"
/>
Refer to Imgix URL parameters reference for all available options.
An image with a width-based srcset
attribute can be rendered using the widths
prop.
<PrismicImage
:field="document.data.myImageField"
:widths="[600, 900, 1200]"
/>
<!--
<img alt="..." src="..." srcset="...?width=600 600w, ...?width=900 900w, ...?width=1200 1200w" />
-->
The widths
prop accepts two special values:
thumbnails
bases the widths on your image field and its responsive views.defaults
bases the widths on the plugincomponents.imageWidthSrcSetDefaults
option and fallbacks to@prismicio/client
defaults if not specified.
<PrismicImage
:field="document.data.myImageField"
widths="thumbnails"
/>
<!-- `srcset` is based on your responsive views
<img alt="..." src="..." srcset="...?width=400 400w, ...?width=800 800w, ...?width=1200 1200w" />
-->
<PrismicImage
:field="document.data.myImageField"
widths="defaults"
/>
<!-- `srcset` is based on the plugin option
<img alt="..." src="..." srcset="...?width=600 600w, ...?width=900 900w, ...?width=1200 1200w" />
-->
See MDN's Responsive Images guide to learn more about srcset
and its variations.
An image with a pixel-density-based srcset
attribute can be rendered using the pixel-densities
prop.
<PrismicImage
:field="document.data.myImageField"
:pixel-densities="[1, 2]"
/>
<!--
<img alt="..." src="..." srcset="...?dpr=1 1x, ...?dpr=2 2x" />
-->
The pixel-densities
prop accepts one special value of defaults
. It bases the pixel densities on the plugin components.imagePixelDensitySrcSetDefaults
option and fallbacks to defaults
if not specified.
<PrismicImage
:field="document.data.myImageField"
pixel-densities="defaults"
/>
<!-- `srcset` is based on the plugin option
<img alt="..." src="..." srcset="...?dpr=1 1x, ...?dpr=2 2x, ...?dpr=3 3x" />
-->
To learn more about srcset
and its variations, see MDN’s Responsive Images guide.
For lower-level use cases, a composable is also available to replicate this component behavior. It uses the same props as options, except the image-component
prop, which is omitted.
import { usePrismicImage } from "@prismicio/vue";
const {
src,
srcset,
alt,
copyright
} = usePrismicImage({ field: document.data.myImageField });
// Not necessary when using the plugin
import { PrismicEmbed } from "@prismicio/vue";
Vue component that renders content from a Prismic embed field.
<PrismicEmbed :field="document.data.myEmbedField" />
This component wraps its output in a <div>
tag. To use another wrapper tag or wrapper component, use the wrapper
prop.
<PrismicEmbed :field="document.data.myEmbedField" wrapper="h1" />
This component's role is to render a Prismic embed field safely. Because Prismic is not able to predict the nature of your embed output, it's your duty to style it accordingly. For that purpose you can target the data attributes generated by <PrismicEmbed>
in your CSS.
/* Style text type embed */
[data-oembed-type="text"] {
/* ... */
}
/* Style YouTube embed */
[data-oembed-provider="YouTube"] {
/* ... */
}
/* Style embed from figma.com */
[data-oembed*="figma.com"] {
/* ... */
}
// Not necessary when using the plugin
import { SliceZone } from "@prismicio/vue";
Vue component that renders content from a Prismic slice zone using Vue components for each type of slice.
For example, if a slice zone contains a Text slice followed by an Images slice, <SliceZone>
will render <TextSlice>
and <ImagesSlice>
in a list.
<SliceZone
:slices="document.data.body"
:components="defineSliceZoneComponents({
text: TextSlice,
images: ImagesSlice,
})"
/>
Alongside the slices
prop, an object of slice type IDs (for example: "text") mapped to its Vue component (for example: <TextSlice>
) should be provided to the components
prop. Components can be supplied in a variety of ways.
To ensure that the map is defined properly — and to handle some edge-cases — we provide defineSliceZoneComponents()
as a helper. We highly recommend using it when defining your components map.
import { defineAsyncComponent } from "vue";
import { defineSliceZoneComponents } from "@prismicio/vue";
import FooSlice from "~/slices/FooSlice";
const components = defineSliceZoneComponents({
// Explicit import
foo: FooSlice,
// Assuming "BarSlice" is registered globally in your Vue application
bar: "BarSlice",
// Async components are also a great way to achieve code splitting
baz: defineAsyncComponent(() => import("~/slices/BazSlice.vue")),
});
Slice components are passed four props:
slice
: The slice object being rendered.index
: The index of the slice within the slice zone.slices
: The list of all slice objects in the slice zone.context
: Arbitrary data passed to the<SliceZone>
'scontext
prop.
Because defining props in Vue.js is verbose, we provide a helper function to do so: getSliceComponentProps()
. With it, a simple slice component could look like this.
<template>
<PrismicRichText :field="slice.primary.text" />
</template>
<!-- Composition API -->
<script setup>
import { getSliceComponentProps } from "@prismicio/vue";
// The array passed to `getSliceComponentProps` is purely optional and acts as a visual hint for you
defineProps(getSliceComponentProps(["slice", "index", "slices", "context"]));
</script>
<!-- Options API -->
<script>
import { getSliceComponentProps } from "@prismicio/vue";
export default {
// The array passed to `getSliceComponentProps` is purely optional and acts as a visual hint for you
props: getSliceComponentProps(["slice", "index", "slices", "context"])
}
</script>
If you have data that needs to be shared with all slice components, provide a value to the context
prop of the <SliceZone>
component. The value will be passed to each slice component as a context
prop.
<SliceZone
:slices="document.data.body"
:components="defineSliceZoneComponents({
text: TextSlice,
images: ImagesSlice,
})"
:context="{ foo: 'bar' }"
/>
By default, a "TODO" component will be rendered with a warning if a component is not provided for a slice type.
This default can be overridden globally using the plugin components.sliceZoneDefaultComponent
option or locally by using the defaultComponent
prop. The default component is passed the same props listed above.
<SliceZone
:slices="document.data.body"
:default-component="() => null"
/>
The default "TODO" component will not be rendered in production (i.e. when process.env.NODE_ENV
is production
).
The <SliceZone>
component renders with no wrapping element around the list of slice components. If you need a wrapper tag or component, you can use the wrapper
prop.
<SliceZone
:slices="document.data.body"
:components="defineSliceZoneComponents({
text: TextSlice,
images: ImagesSlice,
})"
wrapper="article"
/>
@prismicio/vue
provides Vue composables to use with the Composition API to query content from a Prismic repository.
For client-rendered pages
These composables are designed for client-rendered Vue apps or pages. If you are using a Vue framework with server-side rendering (like Nuxt.js), prefer the framework's standard data fetching practices over these composables.
Every query method from a Prismic client, such as getAllByType()
and getSingle()
, is provided as a composable.
import {
useAllPrismicDocumentsByType,
useSinglePrismicDocument,
} from "@prismicio/vue";
const { data: documents } = useAllPrismicDocumentsByType("page");
const { data: settingsDocument } = useSinglePrismicDocument("settings");
Composables return the fetching state in addition to the query result and a refresh function. This allows you to render, for example, a "loading" interface while the client is fetching results or a refresh button to get latest data.
const { data: pages, state, error, refresh } = useAllPrismicDocumentsByType("page")
state
can be one of the following values:
"idle"
: The composable is waiting to query the repository."pending"
: The composable is querying the repository."success"
: The composable successfully queried the repository."error"
: The composable encountered an error while querying the repository.
error
will contain the thrown error that can be a PrismicError
object from @prismic/client
if the composable fails to query the repository. The composable will be in the error
state.
refresh()
is a function that can be awaited. When called the composable will query again the repository.
All composables default to using the @prismicio/client
instance injected by the plugin if you are using it. In any case, you can still provide an explicit @prismicio/client
instance though the method's last parameter options object.
import * as prismic from "@prismicio/client";
const endpoint = prismic.getEndpoint("your-repo-name");
const otherClient = prismic.createClient(endpoint);
const { data: documents } = useAllPrismicDocumentsByType("page", {
client: otherClient
});
Additionally, if a composable requires specific parameters, they can be provided through the same options object. Those parameters are the same as the one used by the related @prismicio/client
method.
const { data: frenchDocuments } = useAllPrismicDocumentsByType("page", {
lang: "fr-fr"
});
usePrismicDocuments()
usePrismicDocuments(params)
A composable that queries content from the Prismic repository.
This composable accepts the same parameters as the client's get()
method.
const { data: documents, state, error, refresh } = usePrismicDocuments();
useFirstPrismicDocument()
useFirstPrismicDocument(params)
A composable that queries content from the Prismic repository and returns only the first result, if any.
This composable accepts the same parameters as the client's getFirst()
method.
const { data: document, state, error, refresh } = useFirstPrismicDocument();
usePrismicDocumentByID(id)
usePrismicDocumentByID(id, params)
A composable that queries a document from the Prismic repository with a specific ID.
This composable accepts the same parameters as the client's getByID()
method.
const { data: document, state, error, refresh } = usePrismicDocumentByID("id");
usePrismicDocumentsByIDs(arrayOfIDs)
usePrismicDocumentsByIDs(arrayOfIDs, params)
A composable that queries documents from the Prismic repository with specific IDs.
This composable accepts the same parameters as the client's getByIDs()
method.
const { data: documents, state, error, refresh } = usePrismicDocumentsByIDs(["id1", "id2"]);
useAllPrismicDocumentsByIDs(arrayOfIDs)
useAllPrismicDocumentsByIDs(arrayOfIDs, params)
A composable that queries all documents from the Prismic repository with specific IDs.
This composable accepts the same parameters as the client's getAllByIDs()
method.
const { data: documents, state, error, refresh } = useAllPrismicDocumentsByIDs(["id1", "id2"]);
usePrismicDocumentByUID(documentType, uid)
usePrismicDocumentByUID(documentType, uid, params)
A composable that queries a document from the Prismic repository with a specific UID and custom type.
This composable accepts the same parameters as the client's getByUID()
method.
const { data: document, state, error, refresh } = usePrismicDocumentByUID("page", "uid");
usePrismicDocumentsByUIDs(documentType, arrayOfUIDs)
usePrismicDocumentsByUIDs(documentType, arrayOfUIDs, params)
A composable that queries documents from the Prismic repository with specific UIDs of a custom type.
This composable accepts the same parameters as the client's getByUIDs()
method.
const { data: documents, state, error, refresh } = usePrismicDocumentsByUIDs("page", ["uid1", "uid2"]);
useAllPrismicDocumentsByUIDs(documentType, arrayOfUIDs)
useAllPrismicDocumentsByUIDs(documentType, arrayOfUIDs, params)
A composable that queries all documents from the Prismic repository with specific UIDs of a custom type.
This composable accepts the same parameters as the client's getAllByUIDs()
method.
const { data: documents, state, error, refresh } = useAllPrismicDocumentsByUIDs("page", ["uid1", "uid2"]);
useSinglePrismicDocument(documentType)
useSinglePrismicDocument(documentType, params)
A composable that queries a singleton document from the Prismic repository for a specific custom type.
This composable accepts the same parameters as the client's getSingle()
method.
const { data: document, state, error, refresh } = useSinglePrismicDocument("settings");
usePrismicDocumentsByType(documentType)
usePrismicDocumentsByType(documentType, params)
A composable that queries documents from the Prismic repository for a specific custom type.
This composable accepts the same parameters as the client's getByType()
method.
const { data: documents, state, error, refresh } = usePrismicDocumentsByType("page");
useAllPrismicDocumentsByType(documentType)
useAllPrismicDocumentsByType(documentType, params)
A composable that queries all documents from the Prismic repository for a specific custom type.
This composable accepts the same parameters as the client's getAllByType()
method.
const { data: documents, state, error, refresh } = useAllPrismicDocumentsByType("page");
usePrismicDocumentsByTag(tag)
usePrismicDocumentsByTag(tag, params)
A composable that queries documents from the Prismic repository with a specific tag.
This composable accepts the same parameters as the client's getByTag()
method.
const { data: documents, state, error, refresh } = usePrismicDocumentsByTag("fruit");
useAllPrismicDocumentsByTag(tag)
useAllPrismicDocumentsByTag(tag, params)
A composable that queries all documents from the Prismic repository with a specific tag.
This composable accepts the same parameters as the client's getAllByTag()
method.
const { data: documents, state, error, refresh } = useAllPrismicDocumentsByTag("fruit");
usePrismicDocumentsByEveryTag(arrayOfTags)
usePrismicDocumentsByEveryTag(arrayOfTags, params)
A composable that queries documents from the Prismic repository with specific tags. A document must be tagged with all of the queried tags to be included.
This composable accepts the same parameters as the client's getByEveryTag()
method.
const { data: documents, state, error, refresh } = usePrismicDocumentsByTag(["fruit", "vegetable"]);
useAllPrismicDocumentsByEveryTag(arrayOfTags)
useAllPrismicDocumentsByEveryTag(arrayOfTags, params)
A composable that queries all documents from the Prismic repository with specific tags. A document must be tagged with all of the queried tags to be included.
This composable accepts the same parameters as the client's getAllByEveryTag()
method.
const { data: documents, state, error, refresh } = useAllPrismicDocumentsByEveryTag(["fruit", "vegetable"]);
usePrismicDocumentsBySomeTags(arrayOfTags)
usePrismicDocumentsBySomeTags(arrayOfTags, params)
A composable that queries documents from the Prismic repository with specific tags. A document must be tagged with at least one of the queried tags to be included.
This composable accepts the same parameters as the client's getBySomeTags()
method.
const { data: documents, state, error, refresh } = usePrismicDocumentsBySomeTags(["fruit", "vegetable"]);
useAllPrismicDocumentsBySomeTags(arrayOfTags)
useAllPrismicDocumentsBySomeTags(arrayOfTags, params)
A composable that queries all documents from the Prismic repository with specific tags. A document must be tagged with at least one of the queried tags to be included.
This composable accepts the same parameters as the client's getAllBySomeTags()
method.
const { data: documents, state, error, refresh } = useAllPrismicDocumentsBySomeTags(["fruit", "vegetable"]);
dangerouslyUseAllPrismicDocuments(params)
A composable that queries content from the Prismic repository and returns all matching content. If no filters are provided, all documents will be fetched.
This composable accepts the same parameters as the client's dangerouslyGetAll()
method.
const { data: documents, state, error, refresh } = dangerouslyUseAllPrismicDocuments();
We recommend caution when using dangerouslyUseAllPrismicDocuments()
. Querying all documents in your repository is not performant, and should only be used in unique documents from the Prismic repository with specific tags. A document must be tagged with all of the queried tags to be included. cases.
Can't find what you're looking for?
Need technical Support? Spot an error in the documentation? Get in touch with us on our Community Forum.