我正在使用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", {...}
但是我所得到的只是[对象承诺]没有我希望显示的数据。
我究竟做错了什么?
最佳答案
您应该define a method in the Vue instance获得API数据。
像这样:
methods: {
getRapidApiData() {
//do the fetch.... etc
}
}
您可以删除
var chuck = [];
,因为它不是必需的,并用chuck
替换this.chuckData
的引用。然后,您可以启动chuckData之类的
chuckData: []