[Vuejs]-Dynamically import images from prop – Vue3 Composition API

2👍

Using Vite, the solution is to use new URL(url, import.meta.url)

For example,

<template>
  <div class="message-wrapper">
    <img :src="imageUrl" :alt="`${imageName}-img`" />
    <p>{{ props.text }}</p>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  text: String,
  imageName: String
})

const imageUrl = computed(
  () => new URL(`/src/assets/${props.imageName}.png`, import.meta.url).href
)
</script>

As a side note the props in props.imageName is unnecessary when used in <template> code. It is automatically stripped so it’s not important to include it.

👤yoduh

0👍

You can try to use require() for that.

For example:

<template>
  <div class="message-wrapper">
    <img
      :src="require(`@/assets/${props.imageName}`)"
      alt="img"
    />
    <p>{{ props.text }}</p>
  </div>
</template>

In this example props.imageName should be the image name with its extensions. For example like, props.imageName = "empty-cart.png"

Leave a comment