Vue.js:在axios.get之后使用方法返回图像

问题描述 投票:0回答:1
<li v-for="people in projectData.employees" :key="people._id">
    <b-img :src="colleagueImages(people)" 
</li>
async colleagueImages(people) {
  console.log(people); // => [email protected]
  let profileImage = await axios.get("http://myapilink.com/image?id=" + people + "&s=200&def=avatar", {
    headers: {
      'accept': 'image/jpeg'
    }
  });
  console.log(profileImage);
  return 'data:image/jpeg;base64,' + btoa(
    new Uint8Array(profileImage.data)
    .reduce((data, byte) => data + String.fromCharCode(byte), '')
  );
}

console.log(profileImage)返回以下内容:

Chrome console.log我正在使用的API是返回Base64图像。

使用我当前的代码,我只在浏览器控制台中收到以下错误:

[Vue警告]:无效道具:对于道具“src”类型检查失败。预期的字符串,得到了承诺。

javascript vue.js promise async-await base64
1个回答
1
投票

由于您没有首先需要渲染的所有数据,因此您必须在之后更改属性。首先,您需要为项目使用Vue组件,因此您的“src”属性将被激活;第二,您在渲染应用程序后开始对项目的请求。请看这个样机。

Vue.component('todo-item', {
  template: `
    <li>
      <label>
        <input type="checkbox"
          v-on:change="toggle()"
          v-bind:checked="done">
        <del v-if="done">
          {{ text }}
        </del>
        <span v-else>
          {{ text }}
        </span>

        <span v-if="like">
            ♥ {{like}}
        </span>
      </label>
    </li>
    `,
  props: ['id', 'text', 'done', 'like'],
  methods: {
    toggle: function(){
        this.done = !this.done
    }
  }
})
let todos = [
      {id: 0, text: "Learn JavaScript", done: false, like: null },
      {id: 1, text: "Learn Vue", done: false, like: null },
      {id: 2, text: "Play around in JSFiddle", done: true, like: null },
      {id: 3, text: "Build something awesome", done: true, like: null }
    ]
const v = new Vue({
  el: "#app",
  data: {
    todos: todos
  }
})

todos.forEach((item) => {
    // This is just a mock for an actual network request
    window.setTimeout(() => {
        item.like = Math.ceil(Math.random() * 100)
    }, Math.random() * 2000)
})

https://jsfiddle.net/willywongi/gsLqda2y/20/

在这个例子中,我有一个基本的todo-list应用程序,每个项目都有一个假的“喜欢”计数,这是异步计算的。设置我的应用程序后,我等待“喜欢”属性值(在我的示例中,我只是等待毫秒的随机值)。

© www.soinside.com 2019 - 2024. All rights reserved.