Combine a variable and text in the img src attribute with Vue.js

Looking to combine a Vue.js variable with an image URL.

This is what I computed:

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

For android builds:

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

Otherwise:

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

Any suggestions on how to concatenate the computed variable with the URL?

I attempted this:

<img src="{{imgPreUrl}}img/logo.png">

Answer №1

Avoid using curly braces (mustache tags) in attributes. Instead, concatenate data like this:

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

Alternatively, you can use the short version:

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

For more information on dynamic attributes, refer to the Vue documentation.

Answer №2

When working on a different project, I discovered the flexibility of utilizing ES6 template literals enclosed in backticks. As a result, for your particular situation, consider implementing the following code snippet:

<a href="`${dynamicLink()}page.html`">

Answer №3

give it a shot

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

Answer №4

Both methods are acceptable to use.

First Method

Concatenate using the `+` operator and enclose the string in single or double quotes.

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

Second Method

Enclose the string with backticks ` and wrap variables within ${variable}. Since imgPreUrl is a method,

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

Answer №5

When managing this from the database, use the following code:

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

Answer №6

To assist you, here is the code snippet I am using to retrieve a gravatar image:

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

Answer №7

Initially, I encountered an error stating Module not found and it was not functioning. After some investigation, I discovered a solution that resolved the issue.

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

I realized that adding '@' at the beginning of the local path was necessary to make it work.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I encountered an error message saying "TypeError: response.json is not a function" while attempting to make a request using fetch in a project involving ReactJS and Node

Currently, I am in the process of developing a webpage using reactjs and have set up a simple REST api/database with nodejs. My main focus right now is on properly utilizing this API from the front end. The objective was to send a JSON payload containing { ...

What is the process for implementing THREE.EdgesGeometry on a model imported using THREE.OBJLoader?

I have been attempting multiple times to add edges in a model loader using the OBJLoader, but I am unable to achieve it. Mloader = new THREE.MTLLoader(); Mloader.setPath( dir ); Mloader.load( mtl_dir, function ( materials ) { ...

Tips for simulating mouse events in Jasmine tests for Angular 2 or 4

New to Jasmine testing, I'm exploring how to test a directive that handles mouse events such as mouse down, up, and move. My main query is regarding passing mouse coordinates from the Jasmine spec to my directive in order to simulate the mouse events ...

Create a visual representation of a hierarchical structure from a JSON data

I am looking to create a tree view using jQuery and JSON. Here is an example of my JSON data for a single folder: [{"id":"076ac97d","path":"\/test\/undefined","name":"undefined","parentDirName":"test","parentDirId":"70b77ddd-6c15"}, .... ] If ...

In JavaScript, a true statement does not trigger a redirect

<label>Username:</label> <input name="username" id="username" type="text" value="testuser"> <label>Password:</label> <input name="password" id="password" type="password" value="test123"> <input value="Submit" name="su ...

Tips for adjusting an svg component to suit various screen sizes

I inserted the following SVG component into my HTML file. It fits perfectly on my tablet, but it's too large for my smartphone. How can we automatically adjust the size of the SVG to fit different screens? <svg viewBox="310 -25 380 450" w ...

Challenges in accessing a specific button when faced with multiple buttons sharing the same class in Protractor

Code in HTML <button type="button" class="btn btn-default btn-sm pull-right" ng-click="move(1)" tabindex="-1"><i class="glyphicon glyphicon-chevron-right"></i></button> I'm looking for a solution in Angular Protractor that wi ...

Using Fetch to send a HTTP POST request from an HTML front-end to a Node.js backend

Apologies for any misuse of terms or words, as I am still in the process of grasping Node.js. Currently, I have both a website running on LiveServer and a Node.js server on the same PC. While I could technically run the website as a Node.js app, my goal i ...

Encountering issues with running NPM on my Ubuntu server hosted on Digital Ocean

After successfully installing node (nodejs), I encountered a persistent error when attempting to use NPM. Despite researching the issue extensively and trying different solutions, I have been unable to resolve it. Here is the error message displayed in th ...

Bug in Chrome causing issues with autofilling fields in AngularJS applications

Seeking a solution to address a bug noticed while utilizing a custom Angular directive in conjunction with Chrome's autofill feature. The directive is designed for a phone number field, automatically adding dashes "-" to enhance user experience by eli ...

Deselect a checkbox that is already selected and choose the current option in the multiselect dropdown

I've created a code that allows for single select in a multiselect dropdown, disabling other options once one is chosen. However, I don't want to disable the checkboxes and would like to uncheck the selected option if a new one is chosen, all whi ...

Encountering the error message "Uncaught TypeError: Unable to assign value to property 'color' of an undefined object"

I'm facing an issue where I am trying to change the color of the button text to "white" when the button is clicked. However, upon clicking the button, I encounter an error that says "Uncaught TypeError: Cannot set property 'color' of undefin ...

Error: The result from Vue GraphQL is missing the movies attribute

I recently started working with Vue and GraphQL as a frontend developer, but I'm encountering an error that says: Missing getMovies attribute on result {movies: Array(20)} Even though the data is being successfully fetched in the response on Chrome& ...

What is the quickest way to implement an instant search feature for WordPress posts?

Today, I have a new challenge to tackle on my website. I am determined to implement an INSTANT SEARCH feature that will search through all of my posts. One great example to draw inspiration from is found here: Another impressive implementation can be se ...

Is there a way to display a JS alert just one time?

How can I display a message to users on LT IE8 encouraging them to upgrade their browser for a better web experience? I only want the message to appear on their first visit, not every time they refresh the page. Is there a solution for this issue? Thank ...

Start the embedded YouTube live stream on autoplay

When it comes to autoplaying a regular YouTube video, there are various solutions available. However, these methods do not always work for livestreams. I attempted to automatically click the embedded link using the following code: <script> var els = ...

Is there a way to make the delete button remove just one item from the local storage?

Is there a way to make the delete button on each item in a list remove only that specific item without deleting the others and also remove it from local storage? I have been trying to figure this out but haven't had any success so far. <div class ...

Leverage the power of regular expressions in JavaScript for organizing and handling source files

Embarking on my coding journey with JavaScript, I have also been exploring the world of Three.js, a webgl library. After watching tutorials and conducting experiments, I am proud to share my latest creation: . In my code, you'll notice that the obje ...

Create a request for an update by utilizing Axios within a React and Material UI environment

I am completely new to React, and my experience with CRUD functionality is limited to ASP.NET MVC. I'm feeling a bit lost as none of the tutorials I've come across seem to cater to my specific situation. The tips I received previously were helpfu ...

Enhanced feature in Mongoose for updating nested array elements

My Schema looks like this: UserSchema: Schema = new Schema({ username: String, password: String, chat: [{ lastSeen: { type: Date, default: Date.now }, room: { type: Schema.Types.ObjectId, ref: 'ChatRoom' } }], }); I ...