[英]calling a function in Vue.js 3 at <template>
我正在學習如何獲取 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
}
讓它按您的意願工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.