【问题标题】:Async and await in VuejsVuejs 中的异步和等待
【发布时间】:2018-01-15 19:16:21
【问题描述】:

我在使用 VueJS、axios、Async/Await with Promise(??) 从 REST-API 检索数据时遇到问题。 我需要调用两个不同的 REST-API。一个是给我一个列表,我可以遍历它,这很好。

<template>
  <div>
  <div v-if="posts && posts.length">
    <div v-for="post of posts">
       {{post.name}}        
       <img :src="getUserPicturePath(post.name)" />
      </div>
    </div>
  </div>
</template>

如您所见,在 v-for 之间的另一个是调用使用 axios 的方法。

<script>
import axios from 'axios'
export default {
  data: () => {
    posts: []
  }
  created() {
  // a method to fill up the post-array
 },
   methods: {
    async getUserPicturePath(name){
      const response = await axios.get('linkToApi'+name)
      console.dir(response.data.profilePicture.path)
      return response.data.profilePicture.path
    }
  }
}
</script>

console.dir(response.data.profilePicture.path)- 部分给出了 profilePicture 的正确路径,但上面的 &lt;template&gt; 中的 &lt;img :src="getUserPicturePath(post.name)" /&gt; 写为 [Object Promise]

任何建议我如何获得路径?

【问题讨论】:

  • 我目前遇到与您完全相同的问题,代码非常相似,我的图像返回src="[object Promise]",您是如何解决这个问题的?

标签: rest promise vue.js async-await axios


【解决方案1】:

你可以选择

<template> 
   ...
   <img :src="img_path" v-if="img_path">
   ...
</template>
<script>
   ...
   data() {
       ...
       img_path: "",
       img: "userImg.png"
   }

   // or however you wish to pass user image and trigger loading
   create() {
      this.getUserPicturePath(this.img)
   },

   methods: {
      getUserPicturePath(name){                 
            axios.get('getImage/'+name)
                .then(response => {
                    this.img_path = response.data.path
                    console.dir(response.data.path)
                })
                .catch(error =>{
                    // ... error
                })                
        },        
   }

【讨论】:

  • 我投了反对票,因为这根本不能直接回答问题,它使用 promises 而不是 async/await 作为解决方法。
  • 我投了反对票,因为有多个个人资料图片被分配给一个 data 属性。或者这个答案是一个独立的组件,不清楚(并且不使用props)。
【解决方案2】:

Vue 无法解析属性中的 Promise,因此您必须这样做。

模板

<div v-for="post of posts">
  ...
  <img :src="post.profilePicture" />
  ...

JavaScript

export default {
  created() {
    this.posts = ...
    await Promise.all(this.posts.map(async post => {
      post.profilePicture = await this.getUserPicturePath(post.name);
    }));
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2021-10-04
    • 1970-01-01
    • 2017-04-17
    • 2018-11-29
    • 2020-12-05
    相关资源
    最近更新 更多