I’m pretty new to vuejs and nuxt and need a little help.
I am trying to fetch some sub menu items from an api when the “▾” is clicked on the ui. I want to show a pending icon while the data loads. The data only needs to be fetched once.
How can I use {data, pending, error} values from nuxt’s useFetch in the template if they are not created until the method is called?
I get reference errors using the below example. I have also tried setting some empty refs as placeholders and updating them once data has been returned but this didn’t work.
<template>
<NuxtLink :to="url">
{{ label }}
<span @click.prevent="getChildren()">▾</span>
</NuxtLink>
<!-- Submenu -->
<div v-if="isExpanded" @click="isExpanded = !isExpanded">
<div>{{ subMenuItems }}</div>
</div>
</template>
<script setup>
const props = defineProps({
label: String,
url: String,
});
// Expand sub items
const isExpanded = ref(false);
const handleExpand = () => {
isExpanded.value = !isExpanded.value;
};
// Fetch sub items.
const getChildren = () => {
handleExpand();
const { data: subMenuItems } = useLazyFetch(() => '/api/items', {
server: false,
});
};
</script>