#How do I dynamically load the image in nuxt 3 that accepts defineProps?

3 messages · Page 1 of 1 (latest)

timber flumeBOT
#

Hi @simple narwhal. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To dynamically load images in Nuxt 3 while using defineProps, you need to make a few adjustments to your code. The issue you're facing is likely related to how Nuxt 3 handles asset imports. Here's how you can modify your code to make it work:

  1. First, import the image using dynamic import:
<script setup lang="ts">
import { ref, onMounted } from 'vue';

const props = defineProps({
  tooltiptext: String,
  image: String,
  buttontext: String,
});

const imageSrc = ref('');

onMounted(async () => {
  if (props.image) {
    const img = await import(`~/assets/${props.image}`);
    imageSrc.value = img.default;
  }
});
</script>
  1. Then, update your template to use the imageSrc ref:
<template>
  <button
    class="mb-2 bg-coffee-500 text-white px-3.5 py-3.5 rounded-full hover:bg-coffee-400 transition duration-300 border border-coffee-900/20"
    v-tooltip.right="tooltiptext"
  >
    {{ buttontext }}
    <img v-if="imageSrc" :src="imageSrc" :alt="tooltiptext" class="h-3.5 w-3.5" />
  </button>
</template>

This approach uses dynamic imports to load the image, which is compatible with Nuxt 3's asset handling. The onMounted hook ensures that the image is loaded after the component is mounted.

Alternatively, if you're using @nuxt/image module, you can simplify this process by using the <NuxtImg> component:

<template>
  <button
    class="mb-2 bg-coffee-500 text-white px-3.5 py-3.5 rounded-full hover:bg-coffee-400 transition duration-300 border border-coffee-900/20"
    v-tooltip.right="tooltiptext"
  >
    {{ buttontext }}
    <NuxtImg v-if="image" :src="image" :alt="tooltiptext" class="h-3.5 w-3.5" />
  </button>
</template>

<script setup lang="ts">
defineProps({
  tooltiptext: String,
  image: String,
  buttontext: String,
});
</script>
#

This method uses the <NuxtImg> component, which handles asset resolution automatically. Make sure you have the @nuxt/image module installed and configured in your Nuxt project for this to work.

For more information on using images in Nuxt 3, you can refer to the following resources:

Remember to adjust the paths and import statements according to your project structure and image locations.

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