amirify
amirify

Reputation: 805

Why image path is not resolved by require() when passed as prop in NuxtJS?

In my NuxtJS project I have a component that recieves an image path as a prop. I tried passing it directly to :src="imageAddress" but it neither resolve nor throws an error. Then I tried to use this path inside require() to resolve it properly. But I get this Nuxt error: Cannot find module '~/assets/icons/crown.png'. The path is correct and I tested that by placing an img element directly in index.vue. Do you have any idea why this happens?
This is how my code is structured:

pages/index.vue
<template>
  <ChildComponent image-address="~/assets/icons/crown.png" />
</template>

___________________________________________________________________

components/ChildComponent.vue
<template>
  <img v-if="imageAddress.length" :src="require(imageAddress)">
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    imageAddress: {
      type: String,
      required: true,
      default: ''
    }
  }
}
</script>

Upvotes: 3

Views: 2701

Answers (2)

Olie Cape
Olie Cape

Reputation: 1056

Just want to share what worked for me. Since using require gives undefined error. I used import instead.

import imageAddress from '~/asset/icons/crown.png';
<template>
  <ChildComponent :image-address="imageAddress" />
</template>

Upvotes: 0

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23480

You can try to make method in ChildComponent:

getUrl (img)  {
  return require(`~/assets/icons/${img}.png`);
}

then in template:

<img :src="getUrl(imageAddress)" alt="" />

Upvotes: 4

Related Questions