Utilizing Dynamic Image Sources in Vue.js with the Help of APIs

Can someone help me figure out how to solve this issue? I have an API that returns a base64 image, and I want to load this image on my site. Any suggestions on where or how I should implement my function?

This is the API call located in the methods:

methods:{
    async getGraph(){
      const body = new FormData();
      body.append('hostname','hostname');
        axios({
          method:'post',
          url:'http://127.0.0.1:8000/api/graph',
          data: body,
          headers:{"Content-Type":'multipart/form-data'}
        }).then(response=>{
                var graphBase64 = Object.values(response.data)[0]
                console.log(graphBase64)
                return graphBase64
        }).catch(function(response){
          console.log(response)
        })
    }
}

And I would like to use it in this way:

<img v-bind:src="getGraph()">

I was considering placing my API call in beforeMounted, but then the site won't load properly. Thank you in advance for any advice, articles, or ideas!

Answer №1

you are getting warm. you are heading in the right direction to make it dynamic, but there's a better way.

async functions return a Promise: check out more information in the MDN documentation.

Instead of directly updating the value, you can create another variable and assign the updated value to that:

<template>
  <img :src="base64" />
</template>

<script>
data() {
  return {
    base64: "",
  }
},

mounted() {
  this.updateBase64()
},

methods: {
  async updateBase64() {
    // perform asynchronous operations
    this.base64 = newValue
  }
}
</script>

For more insights on the mounted() hook, refer to the documentation at https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

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

The "util" module has been extracted to ensure compatibility with browsers. Trying to use "util.promisify" in client code is not possible

Currently, I'm in the process of scraping LinkedIn profiles with the help of this library: https://www.npmjs.com/package/@n-h-n/linkedin-profile-scraper. Listed below is the code snippet that I am using: <script> import { LinkedInProfileScraper ...

Having trouble reaching an element within a successful Ajax call

I have encountered an issue where the element is not being recognized when putting an ajax call inside another ajax call. Here is an example of the code: $.ajax({ url: 'controleFatAcoes.php', type: 'post', dataType: 'h ...

Passing a list of objects containing lists in MVC3

Is it possible for me to send an array of objects, each containing arrays, from JavaScript to a MVC action result method? Essentially, I have a KeyValuePair with keys as arrays of strings and I need to return a list of these KeyValuePairs. In my code, I ha ...

Having trouble with my Express app due to errors popping up because of the order of my routes

app.get('/campgrounds/:id/edit', async (req,res) =>{ const campground = await Campground.findById(req.params.id) res.render('campgrounds/edit', { campground }); }) app.get('/campgrounds/:id', async (req,res) =>{ ...

Is your Angular 2 routing failing to work properly after a page refresh or reload when using gulp?

I've recently started learning Angular 2, and I encountered an issue with routing. During the development phase, I ran my application using npm start. However, after migrating to gulp.js, when I run the application by typing gulp, everything works fin ...

Trouble with text box focus functionality

Can someone help me focus a text box using code? Here is the code snippet: <input></input> <div id="click">Click</div> $(document).ready(function(){ $("#click").live("click", function() { var inputBox = $(this).prev(); $( ...

In order to streamline our production environment, I must deactivate Vue.js devtools, while ensuring they remain active during development mode

Is there a way to prevent users from inspecting the app using devtools in production mode while keeping it enabled for local/development mode? I've tried setting up .env and .env.production files with the VUE_APP_ROOT_API variable but it doesn't ...

Exploring Angular's Dependency Injection

How can I verify that a module has properly loaded its required dependencies? I've added ngAnimate to the module definition, but it doesn't appear to be functioning within the application when it runs. The environment I'm navigating is quite ...

What sets apart optionalDependencies from peerDependencies in the Meta optional?

Why are both marking dependency as optional and what is the specific use-case of each? Is peerDependenciesMeta intended for npm packages while optionalDependencies is meant for projects? For example, in my npm package, certain modules require dependency ...

How can the background color of a DIV be altered based on the values of an array's minimum

Basically, I am fetching values from an array using AJAX. The background color will change from green to red based on the "aht_value". Currently, the colors are displaying correctly because I hardcoded the values in the calculation below. However, I want t ...

live PHP recording of data moving between tables

As a beginner, I am working on a project to organize groups of people on the screen using PHP code. I have managed to list Distribution Lists, Member Lists, and People, but I lack experience in this area. Can anyone provide some guidance on how to proceed? ...

Introducing the new default in Google Chrome: Now accessing window.opener for target="_blank" links after rel="noopener" is the standard feature

Exploring a new attribute called rel="noopener", I discovered that it keeps opened windows unaware of their opener. After some experimentation, I consistently found window.opener === null, only to realize that this is now the default behavior in ...

What is the best way to assign a unique ID to every <td> element within a table using React Js?

Hello everyone. I am currently working on assigning unique ids to each td in a table based on data received through an API. This is what my code looks like so far. CodeSandbox const assignIdsToTableData = (data) => { var items = Object.values(data)[0 ...

Incorporating a TypeScript module into a JavaScript module within a React application

I'm encountering an issue with my React app that was created using create-react-app. I recently added a Typescript module to the project, which is necessary for functionality reasons. Although it will remain in Typescript, I made sure to install all t ...

I'm curious as to why IPC messages from one menu item in Electron can successfully reach my window, but when sent from a different menu item, they do not seem to

I am working on a straightforward application that requires running a background process to fetch some data. I want to display a loading indicator while the data is being retrieved, but I am encountering difficulties implementing this feature. My approach ...

How to eliminate unnecessary space when the expansion panel is opened in material-ui

Is there a way to eliminate the additional space that appears when clicking on the second accordion in material UI? When I open the second accordion, it shifts downward, leaving a gap between it and the first accordion. Any suggestions on how to remove thi ...

The curious case of jQuery.parseJSON() failing to decode a seemingly valid Json string on a Windows-based server

I am currently running a WordPress JavaScript function code on a Linux server that also includes a PHP function called "get_form_data". jQuery.ajax({ type: "POST", url: MyAjax.ajaxurl, data: {action: "get_fo ...

Progress bar displaying during Ajax request

I'm currently working on an Ajax request that uploads images to the Imgur API and I want to implement a progress bar to show users the upload progress. I found some guidance in this thread, but it seems to display only 1 and stop working. This is the ...

The automated test locator in Angular using Protractor is failing to function

I am facing a challenge with my angular web application as there are some elements that are difficult to interact with. One specific element is a checkbox that needs to be checked during testing: ` <div class="row form-group approval_label"> < ...

Error message in Angular js: Unable to load file using XMLHttpRequest

Encountering an error while debugging an Angular JS application in the WebStorm IDE. The error message states: "XMLHttpRequest cannot load file:///C:/Users/../list.html. Cross origin requests are only supported for HTTP." Provided Javascript code : var a ...