templatesasynchronousvuejs3

Is there a way to use async functions in a Vue expression template?


Using Vue3, I'd like to do something like:

<p>Hi {{ getNameAsync() }}</p>

However this is rendering as

<p>Hi "[object Promise]"</p>

Is there a solution?


Solution

  • The result returned by async is of type Promise<>, so {{ getNameAsync() }} will display in the page [Object Promise], to display the correct content, you need to use ref to store the content and use it in the page.

    NOTICE: you can't use {{ await getNameAsync() }} in the page, because Vue templates can't parse Promise directly.

    <template>
      <div>
        <p>Hi {{ name }}</p>
      </div>
    </template>
    
    <script setup lang="ts">
    const name = ref<string>('')
    
    async function getNameAsync() {
      return 'John'
    }
    
    onMounted(async() => {
      name.value = await getNameAsync()
    })
    </script>