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>
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.
The list of hooks available in the Composition API is as follows:
The closest thing to
And, obviously, you want it to be reactive, so it'screating the Options API is to run the code in thesetup()function. However, to avoid protecting the template withv-if="pizzas"you should instantiate it as an empty array.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:
can remain unchanged because we initializedpizzasto an empty array. If you start it the wrong way, you need to set thev-if="pizzas"protection on the root wrapper element.needs to be assigned.value