MrXQ
MrXQ

Reputation: 740

calling a function in Vue.js 3 at <template>

I was learning how to fetch an API and display It's data in a webpage in Vue.js3 the idea is to display the breeds and when user press on one of the breeds it just display a random dog image . however for some reason when I call the function fetchAPI() it gives me this error : enter image description here

but when I assign it to a variable fun and call that variable instead it works why is that ? This is my code :

<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>

Upvotes: 3

Views: 6164

Answers (1)

floodlitworld
floodlitworld

Reputation: 625

You can only use/call a variable/function in the template if you explicitly return it from the setup() function.

So you'd need to change your code to:

return {
  data,
  image,
  fun,
  fetchAPI
}

for it to work as you intend.

Upvotes: 5

Related Questions