3

I have a problem, I want to show a dynamic img but if i write like this :
<img :src="src" alt="img"> It doesn't work,

instead it works if i do : <img src="../assets/img/banana.png" alt="img">

I've already tried whit require but it returns an error : Error: Cannot find module '../assets/img/banana.png'"

folipso
  • 107
  • 1
  • 8

1 Answers1

1

The problem is that there is no information about where the module is located and webpack cannot resolve it.

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

The import() must contain at least some information about where the module is located.

To fix this, you can create a BaseImage component that replaces the dynamic sources that start with a certain path, in this case ../assets/, and let webpack know that information beforehand.

ie.

<template>
  <img
    :src="computedSrc"
    :alt="alt"
    class="BaseImage"
    v-bind="$attrs"
    v-on="$listeners"
  />
</template>

<script>
export default {
  name: 'BaseImage',

  inheritAttrs: false,

  props: {
    src: {
      type: String,
      required: true,
    },

    /**
     * The alt tag is required for accessibility and SEO purposes.
     *
     * If it is a decorative image, which is purely there for design reasons,
     * consider moving it to CSS or using an empty alt tag.
     */
    alt: {
      type: String,
      required: true,
    },
  },

  computed: {
    // If the URL starts with ../assets/, it will be interpreted as a module request.
    isModuleRequest() {
      return this.src.startsWith('../assets/')
    },

    computedSrc() {
      // If it is a module request,
      // the exact module is not known on compile time,
      // so an expression is used in the request to create a context.
      return this.isModuleRequest
        ? require(`../assets/${this.src.replace('../assets/', '')}`)
        : this.src
    },
  },
}
</script>

Replace img with the BaseImage component.

<!-- <img :src="img.src"  :alt="img.alt"> -->
<BaseImage :src="img.src" :alt="img.alt"/>

Revised codesandbox

Ricky Ruiz
  • 25,455
  • 6
  • 44
  • 53