Leveraging the source of an image from asset variables

Lately, I've been experiencing issues with displaying images on my page, specifically when trying to show a list of images.

The problem arises when attempting to store the image URL in a variable or object instead of hardcoding it directly into the src attribute. When I try to reference the URL using :src="myVariable", which contains the URL, it doesn't work as expected.

For example:

<template>
  <div>
    Problem with images
    <img :src="image.url" alt="">
    <img :src='require(image.url)' alt="">
  </div>
</template>

<script>
export default {
  data () {
    return {
      image:
        {
          url: '~/assets/icon.png',
          type: 'asset'
        }
    }
  }

}
</script>

In this scenario, I have experimented with different variations of referencing assets using ~ and @, but encountered errors due to the way the image URL is provided via a variable rather than directly.

I attempted to address this issue by creating an object that includes the image URL and its type (asset/static) and then checking if the type is asset before using require(variable). However, I ran into an error stating:

"Cannot find module '~/assets/icon.png'"

Has anyone found a solution to this problem?

Answer №1

When dealing with binding to an asset variable image, make sure to use the require method. Here's an example:

<img :src="url">
url: require('@/assets/icon.png')

If your JSON file only includes the filename, you can incorporate the require method in the template like this:

<img :src="require('@/assets/' + url)">
url: 'icon.png'

Answer №2

Shoutout to Dan for sharing his brilliant solution with me. I finally have a universal solution for handling images, including their links and types:

image: {
  url: '/any-asset-folder/image.png'
  type: 'asset'
}

Using a ternary operator, the result is:

<img
  :src="image.type === 'asset' 
    ? require('@/assets'+image.url) 
    : image.url"
>

Now, I can seamlessly display images whether they come from assets, static files, or external sources.

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

What is the reason for the lack of user data being saved in studio3t?

I'm struggling to identify the issue in my app development process. I'm creating an application that collects user email and password, storing them in a database. The problem lies in the fact that while user passwords are successfully stored, the ...

Unravel JSON using JavaScript on the web

I encountered an issue while running this code and trying to decode it: var data = JSON.parse({"forms":[{"url":"example.com/example","name":"example"}]}) document.getElementById("name").innerHTML=data.forms.name Instead of the expected value, the returne ...

Step-by-step guide on utilizing the .change method in order to deactivate a

Can someone help me with a quick solution for this issue? I need to know how to disable a select option once the value has been changed. The option should be available on initial load, but after the user selects it for the first time, it should be disable ...

Successful jQuery Ajax request made without the need for JSON parsing

I find it strange that my experience with jQuery's ajax function is completely different from what I'm used to. Below is the javascript code in question: $.ajax({ url: "/myService.svc/DoAction", type: "GET", dataType: "json", su ...

Failure to receive a server response during the AJAX communication

I am facing an issue with my code that is making 3 requests to a server. The code successfully sends the request, but fails when receiving the response. I need help in skipping the first response and only getting the third one. phone.open("POST", '/& ...

Setting up a Form submit button in Angular/TypeScript that waits for a service call to finish before submission

I have been working on setting up a form submission process where a field within the form is connected to its own service in the application. My goal is to have the submit button trigger the service call for that specific field, wait for it to complete suc ...

utilizing Nuxt code in Elixir/Phoenix

Overview In my previous work, I combined frontend development with nuxt and backend support from elixir/phoenix, along with nginx for reverse proxy. Looking to enhance the performance of the system, my goal is now to migrate everything to Elixir/Phoenix. ...

I am sorry, but it seems like there is an issue with the definition of global in

I have a requirement to transform an XML String into JSON in order to retrieve user details. The approach I am taking involves utilizing the xml2js library. Here is my TypeScript code: typescript.ts sendXML(){ console.log("Inside sendXML method") ...

Preventing jQuery from removing child elements while inserting data through ajax

When I try to insert data into an HTML structure using the code below, only one of the elements displays at a time. It seems like when I use Ajax to insert data, the child elements are being removed. How can I prevent this without having to change the stru ...

Uploading and saving data to an object in FaunaDB using React hook forms

I am currently facing an issue with uploading/saving data to an object in FaunaDB. Specifically, I am trying to upload a string to a jobProfile object: data: { "jobProfile": { "image": "" "coverImage": " ...

Using MVC4 and jQuery to unselect items from an Html.CheckboxListFor

In my search page, I am utilizing jQuery to toggle the visibility of different sections based on user input. Specifically, I have a Html.Textbox and Html.CheckboxListFor that are shown or hidden depending on whether there is any input in the textbox or if ...

Which data types in JavaScript have a built-in toString() method?

Positives: 'world'.toString() // "world" const example = {} example.toString() // "[object Object]" Negatives: true.toString() // throws TypeError false.toString() // throws TypeError Do you know of any other data types that wi ...

Having an issue with Vue.js displaying a blank page post running `npm run serve` and configuring it with IIS

Error Message on Empty Page Despite not using History mode and trying numerous solutions, the issue remains unsolved. I initialized a vuejs project with the command vue create my_project. Following that, I attempted to run npm run serve, which successful ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

When loading a page in NodeJS and Express, there are no initial displays, but upon refreshing the page, all data is successfully retrieved

Struggling to solve this issue that has been lingering for a while. I'm currently working on a project where a remote JSON file is loaded into memory, parsed, and the results are displayed on the page (using pug). Everything seems to be working fine ...

Strategies for efficiently retrieving delayed ajax data to display in a Rails view

When working with an API action that takes around 10 seconds to retrieve data, I typically use an alert to ensure the data is successfully fetched. However, my main concern is how to effectively transmit this data to a Rails view for displaying purposes. B ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

Issues with Vuetify not recognizing style adjustments

Trying to modify the design so that buttons display text with capital letters instead of all uppercase. My version of Vue is 3.5.5 I have included src/stylus/main.styl $button-text-transform = 'capitalize' @require '~vuetify/src/stylus/ap ...

Saving a JavaScript array as a Redis list: A step-by-step guide

I'm trying to figure out how to save array values individually in a Redis list instead of saving the whole array as a single value. Any suggestions on how to achieve this? P.S. Please excuse my poor English. var redis = require('redis'), ...

empty responseText from GET request using AJAX

I've been working on a chatbox using AJAX and I've encountered an issue where my xhttp.responseText is coming back empty. In firebug, I can see that the GET request is being sent and the correct text is being returned, but for some reason it&apos ...