#Img src through props.

3 messages · Page 1 of 1 (latest)

brave sphinx
#

Following the docs you can use a relative src for the image tag as the following, ~/assets/img/example.png which then nuxt knows that it's a file that it should import in the build step, how can you add support for this kind of image importing in props?

sullen mistBOT
#

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:

  1. Import the image in the parent component:
<script setup>
import exampleImage from '~/assets/img/example.png'
</script>

<template>
  <YourComponent :image-src="exampleImage" />
</template>
  1. 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

This will enable advanced image handling capabilities in your Nuxt 3 project.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: