Images
<SanityImage>
This module provides a global <SanityImage> component to assist with rendering images from Sanity.
By default, it is a lightweight functional component that turns the given props into a valid image URL. However, if you have @nuxt/image installed, it will automatically use <NuxtImg> for improved performance.
Nuxt Image Integration
When @nuxt/image is installed in your project, <SanityImage> will automatically detect it and render a <NuxtImg> component instead of a regular <img> tag. This allows you to leverage the powerful features of Nuxt Image, such as resizing, format conversion, and optimizations.
To enable the Sanity provider within Nuxt Image, you need to configure it in your nuxt.config.ts:
export default defineNuxtConfig({
image: {
sanity: {
projectId: 'your-project-id',
dataset: 'your-dataset-name'
}
},
sanity: {
// module options
}
})
You can now use <SanityImage> as before, and it will pass all its attributes to <NuxtImg>. All attributes supported by both <NuxtImg> and the Sanity image API can be passed as props.
<template>
<!-- This will render a <NuxtImg> component -->
<SanityImage
asset-id="image-G3i4emG6B8JnTmGoN0UjgAp8-300x450-jpg"
w="300"
h="450"
auto="format"
/>
</template>
Basic Usage
If you are not using @nuxt/image, <SanityImage> will generate a standard <img> tag.
Props
assetId
The Sanity asset ID, which has the format image-G3i4emG6B8JnTmGoN0UjgAp8-300x450-jpg.
- Type: string
- Required
projectId and dataset
These default to the projectId and dataset from the module options, but can be overridden as props.
- Type: string
Image transformation props
All other image transformation options from the Sanity documentation are also valid props.
Example
<template>
<SanityImage
asset-id="image-G3i4emG6B8JnTmGoN0UjgAp8-300x450-jpg"
auto="format"
/>
</template>
Renderless Usage
By passing a default scoped slot, you can use the <SanityImage> component in a renderless fashion to take full control of the rendered markup.
Example
<template>
<SanityImage
asset-id="image-G3i4emG6B8JnTmGoN0UjgAp8-300x450-jpg"
auto="format"
>
<template #default="{ src }">
<img :src="src" />
</template>
</SanityImage>
</template>
Using @sanity/image-url
If the <SanityImage> component does not cover your specific needs, you can use the official @sanity/image-url package. One way to integrate it is through a Nuxt plugin:
import imageUrlBuilder from '@sanity/image-url'
export default defineNuxtPlugin(() => {
const builder = imageUrlBuilder(useSanity().config)
function urlFor(source) {
return builder.image(source).auto('format')
}
return {
provide: { urlFor }
}
})
This will provide a global $urlFor helper that you can use in your templates:
<template>
<img
:src="$urlFor(movie.image).size(426).url()"
:alt="movie.title"
height="426"
width="426"
loading="lazy"
/>
</template>