Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reactive img src in Vue via API

I’m wondering, how should i solve this problem. I have api which is returning base64 image, and after entering the site, i want to load this img, any one have clues how or where should i put my function?

this is my api call which is in 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 want to have it in this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

i was thinking maybe my api call should be in beforeMounted but after the site wouldn’t load
Huge thanks for any clues/articles/ideas !

>Solution :

you are close. you are binding to make it reactive but the wrong way.

async functions returns Promise: MDN docs.

You can instead create another variable instead and assign the value to that:

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

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

mounted() {
  this.getBase64()
},

methods: {
  async getBase64() {
    // do async/promise stuff
    this.base64 = someValue
  }
}
</script>

Docs for the mounted() hook: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading