I've come up with a different solution that works for my specific case. Maybe it could be useful to others too. It's somewhat similar to the lifestyle hook approach, but without the need for it. Additionally, it doesn't require the use of the <Suspense>
tag, which I found to be unnecessary in my scenario.
The concept is to initially return a default value (in this instance, an empty array, though it could be a "Loading..." splash page). Then, once the async
operation has completed, update the reactive property (in this case, the menuItems
array, but it could also be the actual content of the splash page or HTML).
I understand that this approach may not be suitable for all situations, but it's another method that proved effective for me.
Here is a simplified version of the code:
setup () {
const menuItems = ref([])
const buildMenuItems = async () => {
// example: fetch items from server and format them into an array...
}
/* setTimeout(async () => {
menuItems.value = await buildMenuItems()
}, 0) */
// or..
;(async () => {
menuItems.value = await buildMenuItems()
})()
return {
menuItems
}
}
I tested this by intentionally delaying buildMenuItems() by 2 seconds, and everything functioned correctly.
UPDATE: I also came across other techniques (even applicable to non-TypeScript setups): How can I use async/await in the Vue 3.0 setup() function using Typescript
Cheers,
Murray