Does not work Does not work Does not work

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

3.5k views Asked by At

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

There are 3 answers

0
Gbenankpon Arthur On BEST ANSWER

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;
}
2
wangdev87 On

Bind src to the method.

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

in HTML

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

If image variable is name of file

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

You should not use $ in template.