Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
Vue <script setup> Top level await causing template not to render

I'm using the new syntax in Vue 3 and I really like the idea of it, but once I tried to use a top level await I started to run in some problems.

This is my code:

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

As you can see it's not that complicated, the apiGetInventory is just an axios call so I won't bother going into that. The problem is, that if I have this top level await, my template doesn't render anymore, it's just a blank page in my browser. If I remove the two lines of code, it works fine. Also the promise seems to revolve just fine, if I place a console.log(inventory) underneath it I get an array with objects all fine and dandy.

Anyone have a clue what's going wrong here?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Top-level await must be used in combination with Suspense (which is experimental).

You should be able to just do it in onBeforeMount. Not as elegant; but a solid solution. Something like this:

<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 Relatório

0

Using onBeforeMount is good, but there are a couple of other options.

@skirtle suggested in Vue Discord chat to do the initialization inside an async lambda or function (possibly as an IIFE):

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

@wenfang-du suggested in How can I use async/await in the Vue 3.0 setup() function using Typescript to use promise chaining:

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

The benefit of doing so is that the code is run before the beforeMount lifecycle hook.

You additionally need to take care of error handling as appropriate in both cases.

over 4 years ago · Santiago Trujillo Relatório

0

if you need for specific template(routes). You can use router beforeResolve:

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda