3

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?

5
  • Where does the image variable come from? Which error did you get? Your code should work. Commented Oct 29, 2020 at 19:29
  • @BülentAkgül I added the output to my question now. Commented Oct 29, 2020 at 19:50
  • This is wired, and I don't know where f556f8c5 came from. I don't understand how the base path has changed. First, where image variable came from (v-for, data object, method, computed property, prop, store)? Second, instead of img tag, add a <span>{{image}}</span> and see what is the real value. Commented Oct 29, 2020 at 20:08
  • which bundler are you using vite or vue cli ...? Commented Oct 29, 2020 at 20:58
  • @BoussadjraBrahim Yes, Vue CLI and it does something magical with the srcversion as seen in the output, changing the path and add some hash id. Commented Oct 29, 2020 at 22:01

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Bind src to the method.

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

in HTML

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

2 Comments

I got the same problem, exactly the same src path as without the bind.
can you tell me what the error is if you use my answer?
0

If image variable is name of file

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

You should not use $ in template.

1 Comment

That's old code. In ES5+ we can use what I did. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.