我正在学习如何获取 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>
如果您从 setup() 函数显式返回它,则只能在模板中使用/调用变量/函数。
因此,您需要将代码更改为:
return {
data,
image,
fun,
fetchAPI
}
让它按您的意愿工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句