2017-08-08 215 views
2

我無法使用VueJS,axios,帶有Promise(??)的Async/Await從REST-API中檢索數據。 我需要調用兩個不同的REST-API。一個給我一個清單,我可以遍歷它,這很好。異步並等待Vuejs

<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-對之間,呼籲其採用愛可信的方法。

<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,但在上面的<template><img :src="getUserPicturePath(post.name)" />,寫[Object Promise]

任何建議如何才能獲得路徑?

回答

0

你也許可以用

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