0

Say I have v-img component and I want to render image source using require() statement.

<v-img :src="require(`@/some-folder/my-img.png`)"></v-img>

However, my application breaks completely if I don't have my-img.png in the folder.

So far I've tried:

<v-img :src="require(...) || require(...)"></v-img>
<v-img :src="require(...)">
   <template v-slot:placeholder>
      // placeholder component.
   </template>
</v-img>
<v-img :src="resolveHandler()"></v-img>

methods: {
   resolveHandler() {
      let image;
      try { ... } catch (error) { ... } finally { ... };
      return image;
   }
}

None of the above worked. Any suggestion please? Thanks.

passionateLearner
  • 722
  • 1
  • 7
  • 19
  • Does this answer your question? [Dynamic img src URL with "OR" statement not working properly in NUXT component](https://stackoverflow.com/questions/68027817/dynamic-img-src-url-with-or-statement-not-working-properly-in-nuxt-component) – kissu Nov 28 '21 at 00:46
  • @kissu No the `try...catch` approach did not work for me. – passionateLearner Nov 29 '21 at 00:40
  • 1
    @kissu Actually my function was a promise and it wasn't returning a string value. I made it synchronous and now it works. Thank you. – passionateLearner Nov 29 '21 at 02:01

1 Answers1

0

Try this

<template>
  <v-img :src="imageSrc">
    <template #placeholder>
      No image
    </template>
  </v-img>
</template>

<script>
export default {
  ...
  mounted() {
    try {
      this.imageSrc = require(...);
    } catch (e) {
      this.imageSrc = null;
    }
  },
};
</script>