Image formatting
Global helper
This module defines a global <SanityImage>
component to assist with auto-generating your image URLs. It is a lightweight functional component that simply turns the props into a valid image URL.
Props
assetId
The Sanity asset ID (of the form image-G3i4emG6B8JnTmGoN0UjgAp8-300x450-jpg
).
- Type: string
- Required
projectId
and dataset
These default to the projectId
and dataset
passed into the module options but can be overridden.
- Type: string
Image transformation props
All other image transformation options are valid props - see the Sanity documentation for more details.
Example
<template>
<SanityImage
asset-id="image-G3i4emG6B8JnTmGoN0UjgAp8-300x450-jpg"
auto="format"
/>
</template>
Renderless usage
If you pass in a default scoped slot you can use the <SanityImage>
component as a renderless component to allow you to take full control of the functionality.
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
helper doesn't cover your needs, you can use the @sanity/image-url
package. One way to add it to your Nuxt project is through a 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 }
}
})
Then you can use the global $urlFor
helper:
<template>
<img
:src="$urlFor(movie.image).size(426).url()"
:alt="movie.title"
height="426"
width="426"
loading="lazy"
/>
</template>