【发布时间】:2021-09-15 06:18:09
【问题描述】:
我正在学习如何获取 API 并在 Vue.js3 的网页中显示它的数据,这个想法是显示品种,当用户按下其中一个品种时,它只会显示一个随机的狗图像。
但是由于某种原因,当我调用函数fetchAPI() 时,它给了我这个错误:
但是当我将它分配给变量 fun 并调用该变量时,它可以工作
这是为什么 ?
这是我的代码:
<template>
<div class="dog">
<ul class="dog__ul">
<li class="dog__li" v-for="(value, name) in data.message" :key="name"
@click="fun"
//If I put `fetchAPI()` instead of "fun" it throghs an error
>
{{ name }}
</li>
</ul>
<img :src="image" alt="dog picture" class="dog__img">
</div>
</template>
<script>
import { ref , onMounted, onUnmounted } from 'vue';
export default {
setup(){
const data = ref({});
let image = ref(null);
let fun = fetchAPI;
function fetchList(){
fetch("https://dog.ceo/api/breeds/list/all")
.then(response => response.json())
.then(info=>data.value = info)
.catch(err => console.log (err.message))
}
function fetchAPI(){
fetch(`https://dog.ceo/api/breeds/image/random`)
.then(response => response.json())
.then(val=>image.value = val.message)
.catch(err => console.log (err.message))
}
onMounted(() => {
console.log ("Mount : DogAPI Mounted ⭕");
fetchAPI();
fetchList();
});
onUnmounted(() => console.log("unMount: DogAPI Unounted ❌ "));
return {
data,
image,
fun,
}
}
};
</script>
【问题讨论】:
-
您返回一个带有
fun方法的对象,而不是fetchAPI方法。而是写return {data, image, fetchAPI};。 -
@Aluan Haddad 我从
fetchAPI返回image就像我对fetchList所做的那样,我后来添加了fun但在我这样做之前,函数fetchAPI正在工作,你可以通过查看onMounted()来告诉我我调用了fetchAPI函数并且我可以工作但是当我在 中调用它时它没有,你能用解决方案键入代码以便我能更好地理解它吗? -
我不是这么说的。
标签: javascript vue.js vue-component vuejs3