异步并等待Vuejs
问题描述:
我无法使用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]
。
任何建议如何才能获得路径?
答
你也许可以用
<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
})
},
}
去