通过API在Vue中响应img src



我想知道,我应该如何解决这个问题。我有一个返回base64图像的api,在进入网站后,我想加载这个img,任何人都知道我应该如何或将我的函数放在哪里?

这是我在方法中的api调用:

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)
})
}
}

我想把它放在这个:

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

我想也许我的api调用应该在beforeMounted中,但在站点无法加载之后非常感谢您提供任何线索/文章/想法!

您已接近。你一定要让它被动,但方式不对。

async函数返回Promise:MDN文档。

相反,您可以创建另一个变量,并将值分配给它:

<template>
<img :src="base64" />
</template>
<script>
data() {
return {
base64: "",
}
},
mounted() {
this.getBase64()
},
methods: {
async getBase64() {
// do async/promise stuff
this.base64 = someValue
}
}
</script>

mounted()挂钩的文档:https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-示意图

最新更新