我正在使用 vueJS 和rapidapi,我正在尝试使用 vue 显示来自 API 的数据并使用 JS Fetch 方法检索 API。然而,当我运行代码时,我得到的只是启动它的值(即:[])。
<template>
<div>
<div>{{ chuckData }}</div>
</div>
</template>
<script>
var chuck = [];
fetch("https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random", {
method: "GET",
headers: {
"x-rapidapi-host": "matchilling-chuck-norris-jokes-v1.p.rapidapi.com",
"x-rapidapi-key": "***"
}
})
.then(response => response.json()) // Getting the actual response data
.then(data => {
chuck = data;
})
.catch(err => {
console.log(err);
});
export default {
data() {
return {
chuckData: chuck
};
}
};
</script>
我还尝试使用以下内容:
var chuck fetch("https://matchilling-chuck-norris-jokes-v1.p.rapidapi.com/jokes/random", {...}
但我得到的只是 [object Promise],没有我期望显示的数据。
我做错了什么?
最佳答案
你应该define a method in the Vue instance获取您的 API 数据。
像这样:
methods: {
getRapidApiData() {
//do the fetch.... etc
}
}
您可以删除 var chuck = [];
,因为不需要它,并将 chuck
的引用替换为 this.chuckData
。
然后您可以启动chuckData,例如chuckData: []
关于javascript - 在vue中显示来自rapidapi的API数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61186461/