在Vue.js中异步并等待

Joh*_*yen 6 rest promise async-await vue.js axios

我在使用Promise(??)使用VueJS,axios,Async / Await从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>
Run Code Online (Sandbox Code Playgroud)

如您所见,另一种方法是在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>
Run Code Online (Sandbox Code Playgroud)

console.dir(response.data.profilePicture.path)-部分是给正确的路径profilePicture,但<img :src="getUserPicturePath(post.name)" />在上面的<template>,写[Object Promise]

有什么建议我怎么走吗?

小智 -2

你也许可以一起去

<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
                })                
        },        
   }
Run Code Online (Sandbox Code Playgroud)