Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

javascript - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can try to make method in ChildComponent:

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

then in template:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...