Heim  >  Fragen und Antworten  >  Hauptteil

Wie führe ich einen API-Aufruf im erstellten Hook in Vue 3 durch?

Zurück zu Vue nach einer langen Pause. In meiner Lösung verwende ich die Kompositions-API und nach dem Erstellen der Komponente muss ich einige Daten abrufen, damit ich sie später anzeigen kann. In meiner aktuellen Lösung wird die Vorlage vor dem Aufruf gerendert. Wahrscheinlich ein dummer Fehler, aber ich kann ihn immer noch nicht herausfinden (das ist im Vue 2.0-Hook create() klar).

<template>
  <div>
      <div class="row mb-2 border-top border-bottom" v-for="pizza in pizzas" :key="pizza">
        <div class="col-sm-2">
          <img alt="Vue logo" src="../assets/logo.png" style="height: 100px; width: 135px;">
        </div>
        <div class="col-sm-2 mt-4">
          {{pizza.name}}
        </div>
        <div class="col-md offset-md-2 mt-4">
          price
        </div>
        <div class="col-sm-2 mt-4">
          <button class="btn btn-primary" type="submit">Add</button>
        </div>
      </div>
  </div>
</template>

<script setup>
import {api} from "@/api.js"

let pizzas = null

const GetPizzas = async ()=>{
    await api.get('pizza/pizzas/')
    .then(response=>{
        pizzas = response.data
    })
}
GetPizzas()
</script>


P粉744691205P粉744691205320 Tage vor584

Antworte allen(2)Ich werde antworten

  • P粉509383150

    P粉5093831502023-11-05 00:15:26

    您的解决方案应该如您所愿。您的 api 在创建组件时调用,而不是在组件渲染之后调用,因为它没有在 onMounted 挂钩中调用。此外,你应该让披萨具有反应性。

    Antwort
    0
  • P粉004287665

    P粉0042876652023-11-05 00:12:20

    Composition API 中可用的钩子列表如下:

    与Options API的创建最接近的是在setup()函数中运行代码。但是,为了避免使用 v-if="pizzas" 保护模板,您应该将其实例化为空数组。

    而且,显然,您希望它具有反应性,因此它是 ref([]),而不仅仅是 []

    <script setup>
    
    import { ref } from 'vue'
    import { api } from '@/api.js'
    
    const pizzas = ref([])
    
    const GetPizzas = async () => {
      await api.get('pizza/pizzas/').then((response) => {
        pizzas.value = response.data
      })
    }
    GetPizzas()
    
    </script>
    

    注释