Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Vue <configuración de script> El nivel superior espera que la plantilla no se muestre

Estoy usando la nueva sintaxis en Vue 3 y realmente me gusta la idea, pero una vez que traté de usar una espera de nivel superior, comencé a tener algunos problemas.

Este es mi código:

 <template> <div class="inventory"> <a class="btn btn-primary">Test button</a> <table class="table"> <thead> <tr>Name</tr> <tr>Description</tr> </thead> <tbody> <tr v-for="(item, key) in inventory" :key="key"> <td>{{ item.name }}</td> <td>{{ item.description }}</td> </tr> </tbody> </table> </div> </template> <script setup lang="ts"> import { apiGetInventory, GetInventoryResponse } from '@/module/inventory/common/api/getInventory' const inventory: GetInventoryResponse = await apiGetInventory() </script>

Como puede ver, no es tan complicado, apiGetInventory es solo una llamada axios, así que no me molestaré en entrar en eso. El problema es que si tengo este nivel superior en espera, mi plantilla ya no se muestra, es solo una página en blanco en mi navegador. Si elimino las dos líneas de código, funciona bien. Además, la promesa parece funcionar bien, si coloco un archivo console.log (inventario) debajo, obtengo una matriz con objetos muy bien y elegante.

¿Alguien tiene idea de lo que está mal aquí?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

La espera de nivel superior debe usarse en combinación con Suspense (que es experimental).

Debería poder hacerlo en onBeforeMount . No tan elegante; pero una solución sólida. Algo como esto:

 <script setup lang="ts"> import { apiGetInventory, GetInventoryResponse } from '@/module/inventory/common/api/getInventory'; import {ref, onBeforeMount} from 'vue'; const inventory = ref<GetInventoryResponse>() onBeforeMount( async () => { inventory.value = await apiGetInventory() }) </script>
over 4 years ago · Santiago Trujillo Report

0

Usar onBeforeMount es bueno, pero hay un par de otras opciones.

@skirtle sugirió en el chat de Vue Discord hacer la inicialización dentro de una función o lambda async (posiblemente como un IIFE):

 <script setup lang="ts"> let inventory: GetInventoryResponse const loadData = async () => inventory = apiGetInventory() loadData() </script>

@wenfang-du sugerido en ¿Cómo puedo usar async/await en la función setup() de Vue 3.0 usando Typescript para usar el encadenamiento de promesas?

 <script setup lang="ts"> let inventory: GetInventoryResponse apiGetInventory().then(d: GetInventoryResponse => inventory = d) </script>

La ventaja de hacerlo es que el código se ejecuta antes del gancho del ciclo de vida beforeMount .

Además, debe encargarse del manejo de errores según corresponda en ambos casos.

over 4 years ago · Santiago Trujillo Report

0

si necesita una plantilla específica (rutas). Puede usar el enrutador antes de resolver:

 import { apiGetInventory, GetInventoryResponse } from '@/module/inventory/common/api/getInventory' let inventory = false router.beforeResolve(async to => { // Skip if loaded or for specific vue file if (inventory || to.meta?.layout === 404 || to.meta?.layout === 'blank') { return } inventory = await apiGetInventory() })
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!