#Img src through props.
3 messages · Page 1 of 1 (latest)
Hi @brave sphinx. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To support image importing through props in Nuxt 3, you need to use a different approach compared to the static src attribute. The ~/assets/ syntax is not automatically resolved when passed as a prop. Here's how you can handle this:
- Import the image in the parent component:
<script setup>
import exampleImage from '~/assets/img/example.png'
</script>
<template>
<YourComponent :image-src="exampleImage" />
</template>
- In the child component, use the imported image as the
src:
<script setup>
defineProps({
imageSrc: String
})
</script>
<template>
<img :src="imageSrc" alt="Example image" />
</template>
Alternatively, you can use the useImage composable provided by Nuxt Image module to handle dynamic image imports:
<script setup>
import { useImage } from '#imports'
const props = defineProps({
imageSrc: String
})
const img = useImage()
const optimizedSrc = computed(() => img(props.imageSrc))
</script>
<template>
<img :src="optimizedSrc" alt="Example image" />
</template>
This approach allows you to pass the image path as a prop and still benefit from Nuxt's image optimization features.
For more information on using images in Nuxt 3, you can refer to the following resources:
Nuxt 3 Assets Documentation
Nuxt Image Usage Documentation
Remember to install and configure the Nuxt Image module if you haven't already:
npx nuxi@latest module add image