我有这个问题,GIPHY API 总是返回相同的结果。而且我很确定这不是因为我以某种方式存储了以前的结果并一次又一次地发布它。例如,我输入“狗”并要求 5 个结果.. 我得到 5 个狗 gif,然后我刷新页面并重复该过程并得到完全相同的 gif。
每次我提出请求时,是否有一个优雅的解决方案来获取随机 gif?
我想到的解决方案是:当我提出重复请求时,我会(在后台)请求 10 个 gif,然后将这 10 个新 gif 的 5 个新 gif 发布到页面上,但是这个解决方案可能会变得非常混乱所需的 GIF 数量会越来越大。
到目前为止,这是我的代码:
<v-container>
<v-layout text-center wrap>
<v-flex xs12>
<v-img :src="require('../assets/logo.svg')" class="my-3" contain height="200"></v-img>
</v-flex>
<v-text-field label="Search" outlined rounded v-model="searchText"></v-text-field>
<v-btn outlined rounded block @click="findGIF">Search</v-btn>
<div class="gifs" v-show="showGIFs" ref="gifs">
<div v-for="(gif, index) in gifs" :key="index">
<img class="gif" :src="gif.preview" />
</div>
</div>
</v-layout>
</v-container>
</template>
<script>
export default {
data: function() {
return {
searchText: "",
gifs: [],
index: 1,
showGIFs: true
};
},
methods: {
async fetchGIFs(number) {
let apiKey = "myKey"; // deleted to keep it private
let searchEndPoint = "https://api.giphy.com/v1/gifs/search?";
let limit = number;
let gifsArray = [];
let url = `${searchEndPoint}&api_key=${apiKey}&q=${this.searchText}&limit=${limit}`;
try {
let response = await fetch(url);
let json = await response.json();
json.data.forEach(gif => {
gifsArray.push({
url: gif.url,
preview: gif.images.preview_gif.url,
src: gif.images.original.url,
height: gif.images.original.height,
width: gif.images.original.width
});
});
return gifsArray;
} catch (error) {
console.log("Ooops, take a look at this error: " + error);
}
return "I guess something didn't go right here";
},
findGIF() {
let temp = [];
(async () => {
try {
temp = await this.fetchGIFs(5);
this.gifs.push(...temp);
} catch (err) {
console.log("Have a look at this: " + err);
}
})();
}
}
};
</script>
谢谢!