Vue.js img src concatenate variable and text

Javascriptvue.jsVuejs2

Javascript Problem Overview


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">

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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`">

Solution 3 - Javascript

just try

<img :src="require(`${imgPreUrl}img/logo.png`)">

Solution 4 - Javascript

if you handel this from dataBase try :

<img :src="baseUrl + 'path/path' + obj.key +'.png'">

Solution 5 - Javascript

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"
    />

Solution 6 - Javascript

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`">

Solution 7 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionketomView Question on Stackoverflow
Solution 1 - JavascriptDan MindruView Answer on Stackoverflow
Solution 2 - JavascriptArdhiView Answer on Stackoverflow
Solution 3 - JavascriptiliketofuView Answer on Stackoverflow
Solution 4 - JavascriptMostafa AhmedView Answer on Stackoverflow
Solution 5 - JavascriptAndyView Answer on Stackoverflow
Solution 6 - JavascriptBedram TamangView Answer on Stackoverflow
Solution 7 - JavascriptAresView Answer on Stackoverflow