Came back to vue after long break. In my solution im using composition api where I need to fetch some data once the component is created so I can display it later on. In my current solution, template is kinda rendered before the call has been made. Probably stupid mistake but still I cannot figure it out (in vue 2.0 it was clear - created() hook).
<template>
<div>
<div v-for="pizza in pizzas" :key="pizza">
<div >
<img alt="Vue logo" src="../assets/logo.png" style="height: 100px; width: 135px;">
</div>
<div >
{{pizza.name}}
</div>
<div >
price
</div>
<div >
<button 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>
CodePudding user response:
The list of available hooks in Composition API is here:
The closest thing to Options API's created
is running the code in setup()
function. However, to avoid having to guard 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>
Notes:
<template>
can remain the same, since we initialisepizzas
as empty array. If you initiate it as anything falsey, you need av-if="pizzas"
guard on the root wrapper element.ref
s require assignment to their.value
CodePudding user response:
Your solution should work as what you want. Your api called at the moment component was created, not after component rendered cause it's not called in the onMounted hooks. Moreover, you should make pizzas reactive.