I have a Vue 3 single-page component that contains the following script:
export default defineComponent({
props: {
id: String,
},
setup(props) {
const error = ref<boolean>(false)
const thisCategory = ref<CategoryDetails>()
const subcategories= ref<Category[]>()
const fetchData = (categoryId: string) => {
fetchCategoryDetails(categoryId)
.then((v) => {
thisCategory.value = v
subcategories.value = v.child_categories
})
.catch(() => error.value = true)
}
fetchData(props.id || "")
onBeforeRouteUpdate((to) => fetchData(to.params.id as string))
return {
error,
thisCategory,
subcategories,
}
}
})
The function fetchData
is used to retrieve necessary data for the view. It is called twice within setup(): once to load data when the component is initialized, and once again in onBeforeRouteUpdate
to ensure new data is loaded when navigating between links of the same component with different data.
I foresee needing to replicate this behavior in other components and am struggling to abstract it successfully.
An additional challenge arises when getting the ID from props
directly versus using to.params
in the route guard to ensure correct loading of new IDs.
How can I create a single function to handle both initial data loading and navigation changes, which can be easily implemented across various components by simply passing in a function like fetchData
?