我有一个电影角色列表,这是我使用 axios 从对后端的 REST 调用中获得的。我将它们显示在每个角色的引导卡中。我正在尝试做的是在 giphy 中搜索角色名称,并使用 giphy url 作为卡片的 img-src。
当我尝试这个并查看 Vue devtools 内部时,img-src 显示"承诺"。
<template>
<div class="characters">
<b-container>
<b-card-group columns>
<b-card
v-for="character in characters"
v-bind:key="character.id"
:title="character.name"
:img-src="getGiphy(character.name)"
img-alt="Image"
img-top
tag="article"
style="max-width: 20rem;"
class="mb-2"
>
<b-card-text>
This character is a {{character.role}}
</b-card-text>
</b-card>
</b-card-group>
</b-container>
</div>
</template>
我尝试使用:img-src="getGiphy(character.name)"
获取图像源
@Component
export default class Characters extends Vue {
public characters: Character[] = [];
public fields: string[] = ['name', 'role'];
public async getGiphy(name: string) {
const giphyApi: string =
'//api.giphy.com/v1/gifs/search?api_key=xxxxxxxxxxx&limit=1&q=';
const response = await axios.get(giphyApi + name);
return response.data.data[0].image_url;
}
private async created() {
const response = await axios.get('/api/characters');
this.characters = await response.data._embedded.characters;
}
Vue 无法解析属性中的承诺,所以你必须做这样的事情。
模板
<b-card
...
:img-src="character.giphyImage"
...
>
TS
private async created() {
...
await Promise.all(this.characters.map(async character => {
character.giphyImage = await this.getGiphy(character.name);
}));
}