157

I want to concatenate Vue.js variable with image URL.

What I computed:

imgPreUrl : function() {
    if (androidBuild) return "android_asset/www/";
    else return "";
}

If I build for android:

<img src="/android_asset/www/img/logo.png">

Else

<img src="img/logo.png">

How can I concatenate the computed variable with the URL?

I tried it:

<img src="{{imgPreUrl}}img/logo.png">
nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
ketom
  • 2,334
  • 4
  • 17
  • 25

7 Answers7

291

You can't use curlies (moustache tags) in attributes. Use the following to concat data:

<img v-bind:src="imgPreUrl + 'img/logo.png'">

Or the short version:

<img :src="imgPreUrl + 'img/logo.png'">

Read more on dynamic attributes in the Vue docs.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Dan Mindru
  • 5,986
  • 4
  • 28
  • 42
  • "But Vue.js actually supports the full power of JavaScript expressions inside all data bindings": https://vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions – Alexey Sep 12 '17 at 17:40
57

In another case I'm able to use template literal ES6 with backticks, so for yours could be set as:

<img v-bind:src="`${imgPreUrl()}img/logo.png`">
Ardhi
  • 2,855
  • 1
  • 22
  • 31
  • 5
    I have tried this, but it seems that webpack runs before the bindings are processed because my url is outputted to the browser as "@./assets/syndicate_images/34.jpg" – PrestonDocks Dec 18 '18 at 15:29
  • `imgPreUrl` is a variable, not a function. – Blue Apr 23 '19 at 12:27
15

just try

<img :src="require(`${imgPreUrl}img/logo.png`)">
iliketofu
  • 151
  • 1
  • 3
7

Following both method is valid.

Method 1

Concatenate with + sign and wrap string with single/double quotation.

<img :src="imgPreUrl() + 'img/logo.png'">

Method 2

Wrap with backtick ` and wrap variables with ${variable}. As imgPreUrl is a method so,

<img :src="`${imgPreUrl()}img/logo.png`">
Bedram Tamang
  • 3,748
  • 31
  • 27
5

if you handel this from dataBase try :

<img :src="baseUrl + 'path/path' + obj.key +'.png'">
Mostafa Ahmed
  • 474
  • 7
  • 16
2

If it helps, I am using the following to get a gravatar image:

<img
        :src="`https://www.gravatar.com/avatar/${this.gravatarHash(email)}?s=${size}&d=${this.defaultAvatar(email)}`"
        class="rounded-circle"
        :width="size"
    />
Andy
  • 59
  • 2
  • 11
1

For me, it said Module did not found and not worked. Finally, I found this solution and worked.

<img v-bind:src="require('@' + baseUrl + 'path/path' + obj.key +'.png')"/>

Needed to add '@' at the beginning of the local path.

Ares
  • 2,504
  • 19
  • 19