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:
<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 !
CodePudding user response:
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