How to make API call in created hook in Vue 3?
P粉744691205
P粉744691205 2023-11-04 08:48:38
0
2
660

Return to vue after a long break. In my solution I'm using composition api and after creating the component I need to get some data so I can display it later. In my current solution, the template is rendered before calling. Probably stupid mistake but I still can't figure it out (it's clear in vue 2.0 - create() hook).

<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粉744691205
P粉744691205

reply all(2)
P粉509383150

Your solution should look like you want it to. Your api is called when the component is created, not after the component is rendered, because it is not called in the onMounted hook. Also, you should make the pizza reactive.

P粉004287665

The list of hooks available in the Composition API is as follows:

The closest thing to creating the Options API is to run the code in the setup() function. However, to avoid protecting the template with v-if="pizzas" you should instantiate it as an empty array.

And, obviously, you want it to be reactive, so it's

ref([]), not just [].

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

Comments:

  • pizzas to an empty array. If you start it the wrong way, you need to set the v-if="pizzas" protection on the root wrapper element.
  • ref needs to be assigned .value
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template