I've developed a project in Nuxt 3 that features a homepage displaying various products. Users can click on the product title to access the details page, achieved through the use of <NuxtLink>
<NuxtLink :to="{ name: 'slug', params: { slug: product.slug }}">
<p>{{ product.title }}</p>
</NuxtLink>
Upon clicking the link, the [slug].vue
component fetches the product data from the API based on its slug:
const { data } = await useFetch(runtimeConfig.public.api.product.view + `/${slug}`);
This behavior proves advantageous when users directly visit the product details page from external sources like Facebook. However, if the user navigates from the homepage using <NuxtLink>
, I would prefer passing the product object directly to the [slug].vue
component to avoid redundant API calls and enhance user experience.
To achieve this, I have written code within the [slug].vue
component that checks for empty props and determines whether fetching from the API is necessary:
<script setup lang="ts">
const { slug } = useRoute().params;
const runtimeConfig = useRuntimeConfig()
const route = useRoute()
// Define component props
const props = defineProps({
product: null
});
// Computed property to determine necessity of data fetch
const fetchData = computed(() => {
return !props.product; // Fetch data only if props are empty
});
// Data ref to store fetched data
const product = ref(null);
// Fetch data from API if needed
if (fetchData.value) {
const { data } = await useFetch(runtimeConfig.public.api.product.view + `/${slug}`);
product.value = data.value;
}
</script>
However, I am facing challenges in passing the product object from <NuxtLink>
to the props of my [slug].vue
component. Any suggestions on how to accomplish this without overcomplicating the URL with excessive data or resorting to additional storage solutions?
If you have alternative ideas on efficiently passing data to the [slug].vue
component from the homepage, feel free to share them!
Regards