Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 757
Bill Haack Avatar asked Mar 13 '19 23:03

Bill Haack


People also ask

How can I use img src in Vue JS?

To display an image with the img tag in vue, you can use v-bind:src directive, or :src . Or :src for short. Remember that :src expects a JavaScript expression, so if you want to use a string literal in :src you need to wrap the string in quotes.

Is Vue 2 way data binding?

Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. The v-model directive makes two-way binding between a form input and app state very easy to implement.

How does Vue data binding work?

In a data binding process, whenever data is changed, it is reflected automatically by the elements bound to the data. The term data binding is also used in cases where an outer representation of data in an element changes, and the underlying data is automatically updated to reflect this change.

How do you bind variables in Vue?

If we want to bind any variable, we can simply use Vue. js's double curly braces syntax or “Mustache” syntax to bind any variable from the relative component instance. Or, if we want to bind any variable inside an HTML attribute, we can use the v-bind directive.


Video Answer


1 Answers

Please try require

<img class="img-time-matters" :src="require(`../assets/time-comparison-${locale}.png`)">
like image 67
ittus Avatar answered Sep 28 '22 19:09

ittus