Vue img src path does not work the same as :src

Viewed 1967

I use Vue. I try to output an image and it works fine when I use src but not when I use :src.

Works

<img src="../assets/image.png" />

Does not work

<img :src="`../assets/${image}.png`" />

What I've tried, but did not work

  • @ first in the path.
  • ~ first in the path.
  • ./ first in the path.
  • / first in the path.
  • require but it throws an error if the image can't load. I prefer the native broken image icon, which does not break the script.

My output

The variable image contains the filename which in this case would be image.

The output from both version is like below:

<img src="../assets/image.png" data-v-469af010=""> <!-- src -->
<img src="/img/image.f556f8c5.png" data-v-469af010=""> <!-- :src -->

For some reason they differ quite alot.

How can I solve it?

3 Answers

I solved this problem with this:

<img :src="cover(url)" /> // I call a method cover.

// Method cover
cover(url) {
    if (url !== ''){ // You can check any matching expression.
         try {
             url = require('@/assets/img/' + url)
         } catch (e) {
             url = require('@/assets/img/default.jpg'); // I used a default image. 
         }
     }
     else
         url = require('@/assets/img/default.jpg'); // Default image. 
     return url;
}

Bind src to the method.

getImgUrl(image) {
    return `../assets/${image}.png`
  }

in HTML

<img :src="getImgUrl(image)" />

If image variable is name of file

<img :src="'../assets/'+image" />

You should not use $ in template.

Related