Search code examples
data-bindingvuejs2src

Vue JS data binding not working for img src


I am using vue 2 and vue-cli 3. I am trying to bind the src of an tag to a variable in data.

Specifically I am doing the following:

<img class="img-time-matters" :src="`./../assets/time-comparison-${locale}.png`">

export default {
   name: "home",
   components: {},  
   data() {
       return {
           locale: locale // 'en'
       };
   }
}

The binding works

Using Chrome developer tools and examining the network activity I see that the binding works:

http://localhost:8080/assets/time-comparison-en.png

However the resource is not found.

If I remove data binding at hard code the course path to:

<img class="img-time-matters" :src="`./../assets/time-comparison-en.png`">

Vue resolves the resource link to look for the image at:

http://localhost:8080/img/time-comparison-en.74a6f0ca.png

How do I get the Vue to data bind in such a way that it resolves the binding correctly (i.e. time-comparison-en.74a6f0ca.png).

Thanks!


Solution

  • Please try require

    <img class="img-time-matters" :src="require(`../assets/time-comparison-${locale}.png`)">