Vue 中的 Reactive img src via API

Reactive img src in Vue via API

我想知道,我该如何解决这个问题。我有 api 正在返回 base64 图像,进入站点后,我想加载此 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 中,但在网站无法加载之后 非常感谢任何 clues/articles/ideas !

你很接近。您必须使其具有反应性,但方式错误。

async 函数 returns Promise: MDN docs.

您可以改为创建另一个变量并将值分配给该变量:

<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-Diagram