Async and await in Vuejs

I am having problems getting data from REST API using VueJS, axios, Async / Await with Promise (??). I need to call two different REST APIs. One gives me a list and I can iterate over it, which is good.

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

      

The other, as you can see, between v-for, calls a method that uses 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)

- the part gives the correct path to the profile, and <img :src="getUserPicturePath(post.name)" />

above in <template>

, writes [Object Promise]

.

Any suggestion how can I get the path?

+5


source to share


2 answers


Vue cannot resolve promises on properties, so you must do something like this.

template

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

      



JavaScript

export default {
  methods: {
    async getUserPicturePath(post) {
      const response = await axios.get('linkToApi' + post.name)
      post.profilePicture = response.data.profilePicture.path
    }
  }
  created() {
    this.posts = ...
    this.posts.forEach(x => this.getUserPicturePath(x))
  }
}

      

0


source


you can go with



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

      

-2


source







All Articles