Is there a way to show an image fetched from an axios call in a Vuejs img tag? I haven't found any solution that actually works

There are various methods to achieve this. Initially, I planned to save the image in my database and then call it from there to the view. However, I'm unsure about where to store the image and how to properly call it using :src="prizes.image_url".

The image is currently stored on the client-side.

{
    id: 2,
    name: "Merano MC400 Cello",
    description: "Established in 2000, Merano have made it their mission to create affordable, beautifully crafted instruments. They offer brass, wind and stringed instruments all at reasonable prices. They have a large team of artisans who look over every instrument to ensure it maintains high standards. Many of their instruments are aimed at the beginner market but they also offer some fine examples of professional equipment as well.",
    image_url: "../assets/images/c5Cor.png",
    quantity: 3
}
getPrizes() {
  axios.get('http://localhost:3000/prizes').then(response => {
    this.prizes = response.data
    console.log(response.data)
  })
}
<div v-for="prize in prizes" :key="prize.id">
   <div class="card_individual">
      <div class="card-media-container">
         <img class="card_image" :src="prize.image_url" alt="instruments"/>
      </div>
      <div class="card-detail-container">
         <div class="card_title">Win a {{ prize.name }}</div>
      </div>
      <div class="modal-footer">
         <router-link :to="{ name: 'PriceDetail', params: { prizeId: prize.id }}"><button type="button" class="btn btn-primary">{{ cards.btn_text }}</button></router-link>
      </div>
   </div>
</div>

Answer №1

Answer in Brief

All images should be placed within the designated assets folder (or a subfolder). Only include the filename in your JSON data, like this: image_url: "c5Cor.png", and display it using the following code snippet:

<img :src="require('@/assets/' + prize.image_url)" />

Additional Insights

Webpack bundles the assets directory, thereby altering the paths and filenames of its contents. This necessitates the use of require when binding the variable to the src attribute in order to ensure the correct path at runtime.

When referencing client/server environments, it's essential to distinguish between frontend and backend resources—both of which are served from the server. For instance, claiming that an image is stored "client-side" without utilizing mechanisms such as localStorage or indexedDB would be inaccurate. Storing images in Vue's assets directory falls under server-side frontend operations, while database storage is associated with server-side backend functionality.

If your intention is to inquire about the optimal method for storing images—either in the database or as files—it might be more appropriate to phrase it as, "Should I store images in the database or upload them as files?" In most cases, typical websites follow the practice of storing images as files and recording only their filenames in the database. While there is a debate around storing raw image data as blobs in the database, this approach is relatively uncommon in standard web development scenarios. The simpler and more prevalent choice is file storage.

Answer №2

Fetch the image using img tag and save it as a blob:

<img class="card_image" :src="getImageBlob(prize.image_url)" alt="instruments"/>
  <div v-for="prize in prizes" :key="prize.id">
    <div class="card_individual">
      <div class="card-media-container">
        <img class="card_image" :src="getImageBlob(prize.image_url)" alt="instruments"/></div>
      <div class="card-detail-container">
        <div class="card_title">Win a {{ prize.name }}</div>
      </div>
      <div class="modal-footer">
        <router-link :to="{ name: 'PriceDetail', params: { prizeId: prize.id }}"><button type="button" class="btn btn-primary">{{ cards.btn_text }}</button></router-link>
      </div>
    </div>
  </div>
  getPrizes () {
    axios.get('http://localhost:3000/prizes')
      .then(response => (this.prizes = response.data)
  },
  getImageBlob (image_url) {
    return axios.get(image_url).then(response => window.URL.createObjectURL(response.data))
  }

Likewise, if you wish to store this data in your database, you can also save the response.data in the database.

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

Methods used on a server and methods used on a client-side application

In my ASP.NET application using C# 2.0, I have created objects for a database with properties that can be called natively or through a RESTful JSON API. These objects are used to convert data into HTML for display on the website. On the site, there are se ...

Unlocking the Sound: Using a Custom Button to Activate Audio on HTML Video in React

While working on a project, I encountered a small issue: I have a video tag in my code: <video muted autoPlay loop src={video}> I simply want to add a single custom button/control to toggle between muting and unmuting the video. I'm thinking of ...

Error message: "Lazy-loaded modules encounter a TypeError stating that '' is not a function when accessed through NGINX."

Hey, I've got some distribution files for you to check out: AOT-enabled dist with Lazy Modules No AOT Lazy Modules dist AOT without Lazy Modules dist Here's what's been going on: When served locally with webpack-dev-server or live-serve ...

ACL - Utilize ACL in conjunction with the passport authentication system

I am experimenting with node_acl in combination with passport-local. Unfortunately, I am facing an issue when trying to secure the route for the admin-user '/admin', as it keeps redirecting me to the /login page. Below is a simplified version of ...

Dynamically update a dropdown menu with options based on the user's selection from a prior dropdown list using ajax and JSP Servlet

I am working on creating a real-time project for a consultancy and could use some assistance with developing a JSP page. Specifically, I need to allow the user to select a Client (Company name) from a dropdown list. Once a Client is selected, the HR list ...

Checking date entries

After customizing the date format in the Django modelform widget and jQuery datepicker, I encountered an error indicating that the field is not valid. class Sale_Invoice_Main_Page(forms.ModelForm): class Meta: model = SaleInvoice field ...

Tips for managing test cases to execute on various browsers using protractor

unique challenge observing the unique challenge image provided, there are two browsers executing different test scenarios. I aim to execute spec 7 on both active browsers (browser1 and browser2) with an interactive approach like a chat application. After ...

Using lazy loading and $ocLazyLoad for improved performance

Recently, I stumbled upon the $ocLazyLoad third-party Angular module that allows for the lazy loading of JavaScript files. This concept has me a bit perplexed. Can you explain the difference between lazy loading and caching, and why one would choose to l ...

How to use JavaScript to loop through and parse JSON data from Google Maps API

Hey there, I'm a beginner in javascript and I need some help. I am trying to figure out the best way to access a json object called "js" so that I can display different content for each marker on a map. Right now, all my markers are showing the same k ...

Updates to Firebase data do not automatically reflect in Google Charts

I've successfully connected my Firebase to Google Charts, however I am facing an issue in displaying a 'no data' message when there is no data available. Currently, I have set a Firebase data value of 'NA' for a single user, which ...

The presence of Vue refs is evident, though accessing refs[key] results in an

I am facing an issue with dynamically rendered checkboxes through a v-for loop. I have set the reference equal to a checkbox-specific id, but when I try to access this reference[id] in mounted(), it returns undefined. Here is the code snippet: let id = t ...

The schema does not accept fileLink as valid

I'm currently facing an issue with implementing Simple Schema in my Meteor React project. Despite my efforts, I can't seem to make it work as expected. Below is the schema I am using: Comments.schema = new SimpleSchema({ city: { type: S ...

Is there a way to monitor the home button press event within a PhoneGap application?

Hello! I'm curious if there is a way to track when the Home button is pressed on both Android and IOS using phonegap phonegap build. I have looked into events for the home button press, but have only found information on back button events so far. ...

Enter key not triggering submission in jQuery UI autocomplete field

I'm currently working on implementing the autocomplete feature following a tutorial, and while it's functioning, I'm facing an issue with submitting the form when the user selects an item and hits enter. Below is the Coffeescript code that I ...

Creating dynamic axes and series in Ext JS 4 on the fly

I am looking to dynamically generate the Y axis based on a JSON response. For example: { "totalCount":"4", "data":[ {"asOfDate":"12-JAN-14","eventA":"575","eventB":"16","eventC":"13",...}, {"asOfDate":"13-JAN-14","eventA":"234","eventB":"46","even ...

Transform JSON data into a JavaScript object

There is a JSON string in a specific format: [{"A":"SomeStringData","B":1}, {"A":"SomeStringData","B":2}, ... ... ...] It should be noted that this JSON string passes through all online parsers successfully and is considered valid. An attempt is being ...

Getting just the main nodes from Firebase using Angularfire

I'm having trouble figuring out how to print just the parent element names from the structure of my database. The image provided shows the layout, but I can't seem to isolate the parent elements successfully. ...

Is it possible to use both :to="for navigating to a component" and :href="for navigating to a web page" simultaneously in Vue.js 2.6?

I am currently developing a Vue.js application with Vue Router that includes a sidebar menu. I am aiming to achieve the following functionality: When a menu item is clicked, I want to render a component and open a new web page in a new window. Thus far, ...

In the three.js scene, a lone particle stands out, capturing all attention

I am currently working on a project to generate a sphere with particles scattered randomly across its surface. The idea is for these particles to move based on the position of the mouse cursor, creating an effect similar to the image linked here: https://i ...

Angular - Error: Cannot read property 'publishLast' of undefined

My goal is to prevent multiple requests from being created when using the async pipe. I am facing an issue with a request to fetch a user from the API: getUser() { this._user = this.http.get<User>(environment.baseAPIUrl + 'user') ...