【问题标题】:calling a function in Vue.js 3 at <template>在 <template> 调用 Vue.js 3 中的函数
【发布时间】: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


【解决方案1】:

如果您从 setup() 函数显式返回变量/函数,则只能在模板中使用/调用它。

因此您需要将代码更改为:

return {
  data,
  image,
  fun,
  fetchAPI
}

让它按你的意愿工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2018-06-02
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多